我在Symfony2项目中使用JMSDiExtraBundle。
这是我的问题:
Repository.php
abstract class Repository extends DocumentRepository implements ReadOnlyRepositoryInterface {
protected $dm;
protected $repo;
protected $query;
/**
* @InjectParams({
* "dm" = @Inject("doctrine.odm.mongodb.document_manager")
* })
*/
public function __construct(DocumentManager $dm) {
$this->dm = $dm;
parent::__construct($dm, $this->dm->getUnitOfWork(), new ClassMetadata($this->getDocumentName()));
$this->query = $this->dm->createQueryBuilder($this->getDocumentName());
}
}
PostRepository.php
/**
* @Service("post_repository")
*/
class PostRepository extends Repository implements PostRepositoryInterface {
private $uploader;
/**
* @InjectParams({
* "dm" = @Inject("doctrine.odm.mongodb.document_manager"),
* "uploader" = @Inject("uploader"),
* })
*/
public function __construct(DocumentManager $dm, UploaderService $uploader) {
parent::__construct($dm);
$this->uploader = $uploader;
}
}
可以看出,PostRepository需要2个依赖:DocumentManager(后来作为父级注入到Repository)和Uploader。
但似乎Symfony做了一些让它假定PostRepository需要3个依赖的东西:DocumentManager,DocumentManager(再次)和Uploader,因为我明确声明第二个参数需要是一个Uploader实例,因此当然会出错
来自appDevDebugProjectContainer.xml
:
<service id="post_repository" class="BusinessLounge\BlogBundle\Repository\PostRepository">
<argument type="service" id="doctrine_mongodb.odm.default_document_manager"/>
<argument type="service" id="doctrine_mongodb.odm.default_document_manager"/>
<argument type="service" id="uploader"/>
</service>
和appDevDebugProjectContainer.php
:
/**
* Gets the 'post_repository' service.
*
* This service is shared.
* This method always returns the same instance of the service.
*
* @return BusinessLounge\BlogBundle\Repository\PostRepository A BusinessLounge\BlogBundle\Repository\PostRepository instance.
*/
protected function getPostRepositoryService()
{
$a = $this->get('doctrine_mongodb.odm.default_document_manager');
return $this->services['post_repository'] = new \BusinessLounge\BlogBundle\Repository\PostRepository($a, $a, $this->get('uploader'));
}
这是预期的行为吗?或者也许是一个错误?或者我做错了什么?
需要建议!
答案 0 :(得分:2)
您可以删除抽象父类上的@InjectParams,因为它从不实例化。然后,只有你需要的东西被注入你的真实服务。