duanba4254 2017-05-19 13:16
浏览 96
已采纳

DI如何成为Laravel的服务

I hace defined a service class FooService;

<?php

namespace My\Services;

use My\Contracts\Services\FooServiceContract;

class FooService implements FooServiceContract
{

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

which extends an interface, which is registered in my 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);
        }
    }
}

I have created a trait so I can use this elsewhere (my controllers) for example; Trait

<?php
namespace My\Dependencies;

use My\Contracts\Services\FooServiceContract;

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

Controller example;

<?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();
        // ...
    }
}

This all works fine.

But is there a way that I can DI another defined class into the service class so I can give it a class to work with?
From what I have read this just works when you typehint the class in the construct, but I want to be able to typehint an interface.
For example what I want to end up with is;

<?php

namespace My\Services;

use My\Contracts\Services\FooServiceContract;

class FooService implements FooServiceContract
{

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

1条回答 默认 最新

  • dongmei2351 2017-05-19 13:21
    关注

    The doc has good information on what you need. Check out the Binding Interfaces To Implementations part

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题