【问题标题】:Symfony2 JMSDiExtraBundle child service dependency errorSymfony2 JMSDiExtraBundle 子服务依赖错误
【发布时间】:2013-10-11 09:49:16
【问题描述】:

我在 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'));
}

这是预期的行为吗?或者可能是一个错误?还是我做错了什么?

需要建议!

【问题讨论】:

  • 为什么要在抽象类中添加注入?只需删除抽象父类中的 @InjectParams 部分,因为它是抽象的,你无论如何都不能实例化它。
  • 它看起来像一个错误,也许你应该报告它?
  • @m0c 这是一个很好的观点,尽管它并不能真正解决我对这种行为的好奇心。但你的回答挽救了一天:)
  • @MatthieuNapoli 它确实看起来像一个错误,但我再次用谷歌搜索,似乎没有人抱怨它,所以可能是我的代码违反了惯例。

标签: php symfony dependency-injection symfony-2.1


【解决方案1】:

您可以只删除抽象父类上的@InjectParams,因为它永远不会被实例化。然后只有你需要的东西被注入到你的真实服务中。

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多