Laravel界面DI绑定问题

时间:2017-11-10 07:58:29

标签: php laravel laravel-5 dependency-injection

所以基本上我做了一些服务,当然我想用装饰模式缓存我的数据处理:

CampaignService会:

public function __construct(
    CampaignDAO $campaignDao,
    BidServiceInterface $bidService, //notice the interface, here I want to inject the decorated service
    ItemService $itemService
){
    $this->campaignDao = $campaignDao;
    $this->bidService = $bidService;
    $this->itemService = $itemService;
}

CampaignServiceDecorator:

public function __construct(CampaignService $campaignService) //auto-inject
{
    $this->decorated = $campaignService;
}

BidService:

public function __construct(BidDao $bidDao)//auto-inject
{
    $this->bidDao = $bidDao;
}

BidServiceDecorator:

public function __construct(BidService $bidService)//auto-inject
{
    $this->decorated = $bidService;
}

我得到以下内容,一开始可以理解,例外:

  

[Illuminate \ Contracts \ Container \ BindingResolutionException]目标   [App \ Services \ Interfaces \ BidServiceInterface]不可实例化   在构建[App \ Services \ Decorators \ CampaignServiceDecorator时,   应用\服务\ CampaignService会]。

好的,所以我通过定义以下(第一个绑定定义)进行了显式绑定(在AppServiceProvider.php方法中的boot()中):

$this->app->when(CampaignService::class)
    ->needs(BidServiceInterface::class)
    ->give(BidServiceDecorator::class);
[...]
$this->app->bind(BidServiceInterface::class, BidServiceDecorator::class);

但我仍然得到提到的例外,我的自动加载器也是最新的......

基本上我希望我的BidService拥有装饰服务,而不是原始实现。

正如你所看到的那样,没有循环依赖,而且此时我已经被卡住了

P.S:我也尝试过以下命令:

composer dump-autoload

php artisan package:discover

php artisan clear-compiled

php artisan config:clear

唯一的解决方案是在BidServiceDecorator的构造函数中显式注入CampaignService,但这不灵活

0 个答案:

没有答案
相关问题