laravel5.8 自定义契约和服务着的使用Services

1 在app文件下面创建契约Contracts文件夹php

2 建立契约接口接口文件数组

<?php namespace App\Contracts; interface TestContract { public function callMe($controller); }

3 在app文件下面建立服务文夹Servicesapp

4 建立服务类文件ide

<?php namespace App\Services; use App\Contracts\TestContract; class TestService implements TestContract { public function callMe($controller) { dd('Call Me From TestServiceProvider In '.$controller); } }
5 建立服务提供者,接下来咱们定义一个服务提供者TestServiceProvider用于注册该类到容器。建立服务提供者能够使用以下Artisan命令:
php artisan make:provider TestServiceProvider
6 该命令会在app/Providers目录下生成一个TestServiceProvider.php文件,咱们编辑该文件内容以下:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Services\TestService; class TestServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */
    public function boot() { //  } /** * Register the application services. * * @return void * @author LaravelAcademy.org */
    public function register() { //使用singleton绑定单例
        $this->app->singleton('test',function(){ return new TestService(); }); //使用bind绑定实例到接口以便依赖注入
        $this->app->bind('App\Contracts\TestContract',function(){ return new TestService(); });      //或者使用singleton 单例绑定,注册别名
        $this->app->singleton(TestContract::class, TestService::class); $this->app->alias(TestContract::class, 'test'); } }

 

7 注册服务提供者测试

定义完服务提供者类后,接下来咱们须要将该服务提供者注册到应用中,很简单,只需将该类追加到配置文件config/app.phpproviders数组中便可:this

'providers' => [ //其余服务提供者
 App\Providers\TestServiceProvider::class, ],

5 测试服务提供者spa

<?php
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App; use App\Contracts\TestContract;//依赖注入使用
class TestController extends Controller { //依赖注入 public function __construct(TestContract $test){ $this->test = $test; } /** * Display a listing of the resource. * * @return Response * @author LaravelAcademy.org */ public function index() {
//make调用
// $test = App::make('test'); // $test->callMe('TestController');
$this->test->callMe('TestController');//依赖注入调用 } ...//其余控制器动做 }
相关文章
相关标签/搜索