1.定义服务:对某个业务进行逻辑封装以后的一个类php
<?php namespace App\Services; class TestService { public function __construct() { } public function helloWorld() { echo 'hello world'; } }
2.定义服务提供者:须要将定义好的服务类注册绑定,以便在程序中使用app
<?php namespace App\Providers; use App\Services\TestService; use Illuminate\Support\ServiceProvider; class TestServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } public function register() { $this->app->bind('test', function ($app) { return new TestService(); }); } }
3.注册服务提供者到容器:ide
App\Providers\TestServiceProvider::class,
4.使用咱们的服务this
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; /** * */ class TestController extends Controller { public function test1() { app('test')->helloWorld(); } }
$this->app
变量访问容器,而后使用
bind
方法注册一个绑定