Laravel服务容器可以绑定到类和它的所有祖先 - 就像在Symfony中一样

时间:2016-12-19 14:29:09

标签: php laravel laravel-5 ioc-container

我有这样的基类:

class BaseAPI
{

    public function __construct(Client $client, CacheInterface $cache,  $apiBaseUri)
    {
        $this->client = $client;
        $this->apiBaseUri = $apiBaseUri;
        $this->cache = $cache;
    }
}

然后在提供者中:

class APIServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app
        ->when(BaseAPI::class)
        ->needs('$apiBaseUri')
        ->give(env('DEFAULT_API_URI',''));
    }
}

这很有效。 但是当我做祖先的时候:

class GetLocations extends BaseAPI
{
     protected $apiMethodName = 'locations';
     protected $type = 'get';
}

我收到了错误。当然我可以手动为每个祖先编写代码,但是它们有很多,所以问题是:是否有任何绑定的继承机制? 像这样的东西: https://symfony.com/doc/current/service_container/parent_services.html

1 个答案:

答案 0 :(得分:0)

您是否尝试使用界面?

class BaseAPI implements APIInterface
{
}

class APIServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app
        ->when(APIInterface::class)
        ->needs('$apiBaseUri')
        ->give(env('DEFAULT_API_URI',''));
    }
}