【问题标题】:Laravel service container is it possible to bind to class AND all it's ancestors - like in SymfonyLaravel 服务容器是否可以绑定到类及其所有祖先 - 就像在 Symfony 中一样
【发布时间】:2017-05-04 15:12:40
【问题描述】:

我有这样的基类:

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

【问题讨论】:

  • 如果在 symfony 中可以,那么在 Laravel 中也可以

标签: php laravel laravel-5 ioc-container


【解决方案1】:

您是否尝试过为此使用接口?

class BaseAPI implements APIInterface
{
}

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

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2022-01-22
    • 2016-01-31
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多