0

[Symfony 3.4] I have a User entity. I have created a UserRepository that extends EntityRepository class.

I need to inject a service into the repository but it seems to be really hard to achieve. I've tried multiple ways to do it: Constructor Injection, Setter Injection, Custom Factory but none of them seem to work.

I would like to use Setter Injection because the service I need is used only once. This is my implementation:

UserRepository:

class UserRepository extends EntityRepository implements UserLoaderInterface {
    /**
     * @var Utils
     */
    protected $utils;

    /**
     * @param Utils                 $utils
     * @required
     */
    public function setUtils(Utils $utils) {
        $this->utils = $utils;
    }
    [...]
}

services.yml:

_defaults:
        autowire: true      
        autoconfigure: true 
        public: false

AppBundle\:
    resource: '../../src/AppBundle/*'
    exclude: '../../src/AppBundle/{Entity}'

AppBundle\Repository\UserRepository:
        calls:
           - [setUtils, ['@AppBundle\Common\Utils']]

It seems that the call to setUtils is never done, in fact the parameter $utils is always null.

Yes, I've used both the @required annotation and the call in the services.yml but none works.

Do you understand where my problem is? Or maybe a better solution? Thank you very much

  • The best approach is to plugin your own [repository factory](https://symfony.com/doc/master/bundles/DoctrineBundle/configuration.html). Second best is to have your repository extend from ServiceEntityRepository. Otherwise, you can use the old fashion method of using a container service factory. Lots of examples out there. – Cerad Apr 11 '18 at 13:32
  • I'm also guessing that rather than injecting your repository you are using $entityManager->getRepository(User::class) ? – Cerad Apr 11 '18 at 13:49
  • Well the method where I need my service is the loadUserByUsername, used by Symfony for the login, so, for this specific case, I'm not using the getRepository method. Now I try one of the solutions you have written... – Matteo Busetto Apr 11 '18 at 14:04
  • You saved my time! I didn't know about the ServiceEntityRepository. I've used it and now my service is injected correctly with Construction Injection, thank you very much. Please, answer the question and I will accept it – Matteo Busetto Apr 11 '18 at 14:11
  • Just go ahead and up vote the accepted answer here: https://stackoverflow.com/questions/49158947/symfony-inject-doctrine-repository-in-service/49168332#49168332 – Cerad Apr 11 '18 at 14:19
  • Different solution for this problem - https://www.tomasvotruba.cz/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/ – M. Kebza Apr 12 '18 at 12:11

0 Answers0