Symfony2: How to access to service from repository

后端 未结 8 1690
有刺的猬
有刺的猬 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'
    
    0 讨论(0)
  • 2020-12-31 14:05

    Are you sure that is a good idea to access service from repo?

    Repositories are designed for custom SQL where, in case of doctrine, doctrine can help you with find(),findOne(),findBy(), [...] "magic" methods.

    Take into account to inject your service where you use your repo and, if you need some parameters, pass it directly to repo's method.

    0 讨论(0)
提交回复
热议问题