Skip to content

Instantly share code, notes, and snippets.

@ASKozienko
Last active August 29, 2015 14:00
Show Gist options
  • Save ASKozienko/ee22fbc2bb8705ba95c4 to your computer and use it in GitHub Desktop.
Save ASKozienko/ee22fbc2bb8705ba95c4 to your computer and use it in GitHub Desktop.
# app/config/config.yml
doctrine:
    orm:
        entity_managers:
            default:
                repository_factory: doctrine.orm.repository_factory.container_aware
# services.yml
doctrine.orm.repository_factory.container_aware:
   class: Doctrine\ORM\Repository\ContainerAwareRepositoryFactory
   arguments:
      - @service_container
<?php
namespace Doctrine\ORM\Repository;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ContainerAwareRepositoryFactory extends DefaultRepositoryFactory
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function getRepository(EntityManagerInterface $entityManager, $entityName)
    {
        $repository = parent::getRepository($entityManager, $entityName);

        if ($repository instanceof ContainerAwareInterface) {
            $repository->setContainer($this->container);
        }

        return $repository;
    }
}
<?php
namespace Acme\DemoBundle\Entity;
 
use Doctrine\ORM\EntityRepository;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
 
class DemoRepository extends EntityRepository implements ContainerAwareInterface
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
    
    public function getContextIUseWithEveryQuery()
    {
        return $this->container->get("........");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment