Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i inject a service into an entity repository Symfony2 doctrine?

how can i inject a service into an entity repository with the dependency injection?

i try like this:

<service id="rp.repository.user" class="RP\CoreBundle\Repository\UserRepository" 
factory-service="doctrine.orm.entity_manager" factory-method="getRepository">
  <call method="setSecurityContext">
    <argument type="service" id="security.context"/>
  </call>
</service>

but the setSecurityContext it's never called Plz help

like image 873
EAdel Avatar asked Feb 03 '12 12:02

EAdel


1 Answers

Injecting a service into a repository isn't recommended, since it breaks Separation of Concerns. Instead, you should use a service class that calls the repository. Based on your comment, a simple work flow would look like this:

  • Define UserService class, and register it as a service.
  • Inject security.context into UserService
  • Define UserService::getUsers() (or whatever you want the method to be). It's here in the method that you would use security.context to set criteria for the query. You could either pass the criteria directly to your UserRepository::getUsers() method, or build the DQL in the UserService object and pass it to UserRepository.
  • UserService::getUsers() returns whatever UserRepository::getUsers() returns.

This is how I like to handle situations like these, but for the sake of completeness, you could also use simple setter injection on your repository. You would fetch the repository through the entity manager (and not from the service container as in your question), and simply call $userRepository->setSecurityContext($this->get('security.context')).

like image 151
Steven Mercatante Avatar answered Nov 06 '22 03:11

Steven Mercatante