duanba4254
2017-05-19 13:16 阅读 88
已采纳

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条回答 默认 最新

相关推荐