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
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:
UserService
class, and register it as a service.security.context
into UserService
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'))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With