DI如何成为Laravel的服务

时间:2017-05-19 13:16:39

标签: php laravel laravel-5 dependency-injection

我定义了一个服务类FooService;

<?php

namespace My\Services;

use My\Contracts\Services\FooServiceContract;

class FooService implements FooServiceContract
{

    public function doSomething()
    {
        return 'fubar';
    }
}

扩展了一个接口,该接口在我的AppServiceProvider

中注册
<?php

namespace My\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

    private $singletons = [
        \My\Services\FooContract::class => \My\Services\FooService::class,
    ];


    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        CollectionMacros::init();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerLogger();

        foreach ($this->singletons as $abstract => $concrete) {
            $this->app->singleton($abstract, $concrete);
        }
    }
}

我已经创建了一个特性,所以我可以在别处使用它(我的控制器); 性状

<?php
namespace My\Dependencies;

use My\Contracts\Services\FooServiceContract;

trait TheFooService
{
    protected function getDashboardService()
    {
        return app(FooServiceContract::class);
    }
}

控制器示例;

<?php 
namespace My\Http\Controllers\Billing;

use My\Http\Controllers\Controller;
use My\Dependencies\TheFooService;


class BarController extends Controller
{
    use TheFooService;

    public function hello()
    {
        $a = $this->TheFooService()->doSomething();
        // ...
    }
}

一切正常。

但是有没有办法可以将DI另一个定义的类添加到服务类中,这样我就可以给它一个类了? 从我所读到的内容中,只有在构造中键入类时才能正常工作,但我希望能够键入接口。
例如,我想要最终得到的是;

<?php

namespace My\Services;

use My\Contracts\Services\FooServiceContract;

class FooService implements FooServiceContract
{

    public function __construct(BobInterface $randonClass)
    {
        $this->name = $randomClass;
    }
}

1 个答案:

答案 0 :(得分:0)

该文档提供了您需要的信息。查看Binding Interfaces To Implementations部分

https://laravel.com/docs/5.4/container#binding-basics