Symfony2: How to access to service from repository

后端 未结 8 1687
有刺的猬
有刺的猬 2020-12-31 13:08

I have class ModelsRepository:

class ModelsRepository extends EntityRepository
{}

And service

container_data:
 class:               


        
8条回答
  •  醉梦人生
    2020-12-31 14:03

    I strongly agree that this should only be done when absolutely necessary. Though there is a quite simpler approach possible now (tested with Symfony 2.8).

    1. Implement in your repository "ContainerAwareInterface"
    2. Use the "ContainerAwareTrait"
    3. adjust the services.yml

    RepositoryClass:

    namespace AcmeBundle\Repository;
    
    use Doctrine\ORM\EntityRepository;
    use Symfony\Component\DependencyInjection\ContainerAwareInterface;
    use Symfony\Component\DependencyInjection\ContainerAwareTrait;
    use AcmeBundle\Entity\User;
    
    class UserRepository extends EntityRepository implements ContainerAwareInterface
    {
    
        use ContainerAwareTrait;
    
        public function findUserBySomething($param)
        {
            $service = $this->container->get('my.other.service');
        }
    
    }
    

    services.yml:

    acme_bundle.repository.user:
        lazy: true
        class: AcmeBundle\Repository\UserRepository
        factory: ['@doctrine.orm.entity_manager', getRepository]
        arguments:
            - "AcmeBundle:Entity/User"
        calls:
            - method: setContainer
              arguments:
                - '@service_container'
    

提交回复
热议问题