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

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

2 创建契约接口接口文件

<?php

namespace App\Contracts;

interface TestContract
{
    public function callMe($controller);
}

3 在app文件下面创建服务文夹Services

4 创建服务类文件

<?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数组中即可:

'providers' => [

    //其他服务提供者

    App\Providers\TestServiceProvider::class,
],

5 测试服务提供者

<?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');//依赖注入调用 } ...//其他控制器动作 }

 

posted @ 2019-07-17 15:32  CandyChen  阅读(779)  评论(0)    收藏  举报