我正在玩一些不同的设计模式,以便更多地了解它们,并开始使用DI容器。
$container = new \League\Container\Container();
$container->add("config", function(){
return new Config(APP_ROOT . "/config.json");
});
$container->add("GoogleBooks", GoogleBooksProvider::class)
->withArgument( $container['config'] );
$container->add("books", BookRepository::class);
// empty array, as expected
var_dump($container['books']->getProviders());
// this line doesn't add the provider
$container['books']->addProvider( $container['GoogleBooks'] );
// empty array, should expect to have one entry, GoogleBooksProvider
var_dump($container['books']->getProviders());
public function addProvider( iProvider $provider ) {
$this->_providers->push($provider);
return $this;
}
这不能按预期工作,代码注释中描述的问题。但是,如果我交换
$container['books']->addProvider( $container['GoogleBooks'] );
与
$container['books'] = $container['books']->addProvider( $container['GoogleBooks'] );
通过将GoogleBooksProvider存储在BookRepository中,它可以正常工作。为什么我需要一个赋值运算符才能使其正常工作?
如果我这样做而不将其放入容器中,它可以正常工作,没有赋值操作符。
$br = new BookRepository();
$br->addProvider( new GoogleBooksProvider($container['config']) );
// shows GoogleBooks is in the _providers array
var_dump($br->getProviders());
答案 0 :(得分:0)
由于您添加,而不是共享该服务,因此每次访问时都会获取BookRepository
的新实例容器:
var_dump($container['books'] === $container['books']); // false
如果您想要分享BookRepository
,则需要使用此功能:
$container->add("books", BookRepository::class, true);
或(更短)
$container->singleton("books", BookRepository::class);