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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?