0

I've seen a huge amount of projects that uses doctrine and some of them inject the container or other services inside a repository. I've seen also some questions here that talk about container inside a repository:

I got only problem adding container o other services to a repository or an entity. I think there could be some side effects. For example I cannot reuse some code if it depends on a service that is not available in a particular context. For example if my repository depends on Symfony\Component\HttpFoundation\Request it cannot be used inside a command.

Can be a better solution the creation of a service instead of a coupled repository?

Community
  • 1
  • 1
sensorario
  • 20,262
  • 30
  • 97
  • 159

1 Answers1

1

There are some example of how to create Entity managers (or repository), relevant is as described in FOSUserBundle where doctrine Entity manager has been injected as object manager inside the Dependency injection.

    if ('custom' !== $config['db_driver']) {
        if (isset(self::$doctrineDrivers[$config['db_driver']])) {
            $loader->load('doctrine.xml');
            $container->setAlias('fos_user.doctrine_registry', new Alias(self::$doctrineDrivers[$config['db_driver']]['registry'], false));
        } else {
            $loader->load(sprintf('%s.xml', $config['db_driver']));
        }
        $container->setParameter($this->getAlias().'.backend_type_'.$config['db_driver'], true);
    }
    if (isset(self::$doctrineDrivers[$config['db_driver']])) {
        $definition = $container->getDefinition('fos_user.object_manager');
        $definition->setFactory(array(new Reference('fos_user.doctrine_registry'), 'getManager'));
    }

In this case there are UserManager instead of repository that have the same role.

In this example all services has been initialized and injected directly inside the dependency injection

It is more powerful to call (private) services directly inside the bundle construction / or "compilation" (the dependency injection) instead of colling container inside services

mduvernon
  • 498
  • 3
  • 13