Symfony 3将服务注入实体存储库


Symfony 3 Inject service into entity repository

我尝试将memcached服务注入实体存储库,但我的变体不起作用。

services:
  work.repository.company:
    class: WorkBundle'Repository'CompanyRepository
    factory: ['@doctrine.orm.entity_manager', getRepository]
    arguments:
        - 'WorkBundle:Company'
    calls:
        - [setCacheService, ['@memcache.default']]

CompanyRepository具有setter setCacheService,但未调用它。

class CompanyExtension extends 'Twig_Extension
{
    /**
     * @var EntityManager
     */
    private $em;
    public function setEntityManager(EntityManager $entityManager)
    {
        $this->em = $entityManager;
    }
    public function getFunctions()
    {
        return array(
            new 'Twig_SimpleFunction('getCompaniesCount', array($this, 'getCompaniesCount'))
        );
    }
    /**
     * @return integer
     */
    public function getCompaniesCount()
    {
        return $this->em->getRepository('WorkBundle:Company')->getActiveCompaniesCount();
    }
    public function getName()
    {
        return 'work_company_extension';
    }
}

为什么这个代码不起作用?

您是否在WorkBundle:Company实体中注册了repositoryClass?您的实体应该包含类似的内容:@ORM'Entity(repositoryClass="Work'Company")或yaml等价物

您应该让Symfony通过将work.repository.company注入您的Twig扩展来创建存储库。