palmic
palmic

Reputation: 1856

Symfony - Inject and access DIC service in Doctrine EntityRepository

This is relevant to legacy project written in Symfony 2.2.1, doctrine 2.3.3.

I need to access DIC @service in one of EntityRepository classes.

Am i able to inject this service, or container into it via some event listeners or somehow else?

I dont want to inject it into Entity, but particular EntityRepository.

Upvotes: 2

Views: 107

Answers (2)

palmic
palmic

Reputation: 1856

Ok, this is really not clean solution, but it works even if you want to keep getting the repo by $entityManaget->getRepository(). Since the project will be deprecated soon, its good enough...

Just add this DIC getter to your EntityRepository class and you are able to get any DIC service in any Repository in project...

protected function getDICService($serviceName)
{
    /** @var \AppKernel $kernel */
    $kernel = $GLOBALS['kernel'];
    $container = $kernel->getContainer();
    return $container->get($serviceName);
}

Upvotes: 0

Mocrates
Mocrates

Reputation: 209

You can try to declare your Repo as service and add calls to inject your other service

#services.yml
entity.repo :
   class: 'YourRepoNamespace'
   factory-service: 'doctrine.orm.default_entity_manager'
   factory-method: 'getRepository'
   arguments: ['YourEntityNamespace']
   calls:
     - ['setOtherService', ['@other_service']] 

Upvotes: 2

Related Questions