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

fre*_*nzy 5 php ioc-container laravel laravel-5

我有这样的基类:

class BaseAPI
{

    public function __construct(Client $client, CacheInterface $cache,  $apiBaseUri)
    {
        $this->client = $client;
        $this->apiBaseUri = $apiBaseUri;
        $this->cache = $cache;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在提供者:

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

那很有效.但是当我做祖先的时候:

class GetLocations extends BaseAPI
{
     protected $apiMethodName = 'locations';
     protected $type = 'get';
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*ruk 0

您是否尝试过使用接口来实现此目的?

class BaseAPI implements APIInterface
{
}

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