title: Symfony - Wrapper/Helper classes having access to entity's repository
body: <p>Alright so I'm converting a small laravel project to symfony (will get bigger, and the bundling architecture symfony uses will be ideal)</p>
  
  <p>I'm apparently spoiled with laravels facades and eloquent working with existing databases almost right out of the box.</p>
  
  <p>I can't find the most appropriate way to have a wrapper or "helper" class get access to an entities repository.</p>
  
  <p>first let me give a few examples then I will explain what I have attempted. (I'm willing to bounty some points for a good answer but unfortunately the time constraints on the project can't exactly wait)</p>
  
  <p>So in laravel I had all my model classes. Then I created some wrapper / helper classes that would essentially turn the data into something a little more usable (i.e. multiple queries and objects containing more versatile information to work with). And with the magic of facades I could call upon each model and query them without and dependencies injected into these "Helper" classes. keeping them very lean. In symfony it appears the ideal solution is to put all of your reusable database logic in repositories, ok.</p>
  
  <p>In symfony I'm surrounded by Inversion of Control (IoC); which is fine but design pattern is failing to be intuitive for me to fully figure this scenario out. I have tried to create services out every single repository, which works great if being called from a controller or other Dependency Injected (DI) service. But in a standard php class, it appears my hands are tied without passing entity manager to each helper class's constructor. *shivers*</p>
  
  <p>The first limitation is I have zero ability to change the schema of the existing tables (which obviously doesn't change the problem, just don't want anyone to suggest altering the entities).</p>
  
  <p>So how does one accomplish this.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>so thanks to @mojo's comment I've pulled off what I wanted to do. Still looking for a better alternative if it exists. (see edit 2 below)</p>
  
  <p>currently I have:</p>
  
  <p><strong>config.yml docterine.orm.entity_managers:</strong></p>
  
  <pre><code>entity_managers:
       default:
           auto_mapping: true
           connection: default
       asterisk:
           connection: asterisk
           mappings:
               AsteriskDbBundle:  ~
       asteriskcdr:
           connection: asteriskcdr
           mappings:
               AsteriskCdrDbBundle:
  </code></pre>
  
  <p><strong>service.yml</strong></p>
  
  <pre><code>services:
      app.services.doctrine.entitymanager.provider:
          class: AppBundle\Services\EntityManagerProvider
          arguments: [@doctrine]
          tags:
               - {name: kernel.event_listener, event: kernel.request, method: onKernelRequest}
  </code></pre>
  
  <p><strong>EntityManagerProvider</strong></p>
  
  <pre><code>namespace AppBundle\Services;
  use Doctrine\Bundle\DoctrineBundle\Registry as DoctrineRegistry;
  use Doctrine\ORM\EntityManager;
  use Symfony\Component\Config\Definition\Exception\Exception;
  
  class EntityManagerProvider
  {
      /** @var  DoctrineRegistry */
      private static $doctrine;
  
      public function __construct(DoctrineRegistry $doctrine)
      {
          static::$doctrine = $doctrine;
      }
  
      /**
       * @param $class
       * @return EntityManager
       */
      public static function getEntityManager($class)
      {
          if(($em = static::$doctrine-&gt;getManagerForClass($class)) instanceof EntityManager == false)
              throw new Exception(get_class($em) . ' is not an instance of ' . EntityManager::class);
  
          return $em;
      }
  
      // oh man does this feel dirty
      public function onKernelRequest($event)
      {
          return;
      }
  }
  </code></pre>
  
  <p><strong>Example Controller</strong></p>
  
  <pre><code>$extension = Extension::createFromDevice(DeviceRepository::findById(92681));
  </code></pre>
  
  <p><strong>ExtendedEntityRepository</strong></p>
  
  <pre><code>namespace AppBundle\Entity;
  use AppBundle\Services\EntityManagerProvider;
  use AppBundle\Utils\DateTimeRange;
  use Doctrine\DBAL\Query\QueryBuilder;
  use Doctrine\ORM\EntityManager;
  use Doctrine\ORM\Mapping\ClassMetadata;
  use Symfony\Component\Config\Definition\Exception\Exception;
  
  class ExtendedEntityRepository extends \Doctrine\ORM\EntityRepository
  {
      /** @var  ExtendedEntityRepository */
      protected static $instance;
  
      public function __construct(EntityManager $entityManager, ClassMetadata $class)
      {
          parent::__construct($entityManager, $class);
  
          if(static::$instance instanceof static == false)
              static::$instance = $this;
      }
  
      // some horribly dirty magic to get the entity that belongs to this repo... which requires the repos to have the same name and exist one directory down in a 'Repositories' folder
      public static function getInstance()
      {
          if(static::$instance instanceof static == false) {
              preg_match('/^(.*?)Repositories\\\([A-Za-z_]*?)Repository$/', static::class, $match);
              $class = $match[1] . $match[2];
              $em = EntityManagerProvider::getEntityManager($class);
              static::$instance = new static($em, $em-&gt;getClassMetadata($class));
          }
          return static::$instance;
      }
  
      public static function findById($id)
      {
          return static::getInstance()-&gt;find($id);
      }
  
      public static function getQueryBuilder()
      {
          return static::getInstance()-&gt;getEntityManager()-&gt;createQueryBuilder();
      }
  
      public static function getPreBuiltQueryBuilder()
      {
          return static::getQueryBuilder()-&gt;select('o')-&gt;from(static::getInstance()-&gt;getClassName(), 'o');
      }
  
      public static function findByColumn($column, $value)
      {
          //if($this-&gt;getClassMetadata()-&gt;hasField($column) == false)
          //    throw new Exception($this-&gt;getEntityName() . " does not contain a field named `{$column}`");
          return static::getPreBuiltQueryBuilder()-&gt;where("{$column} = ?1")-&gt;setParameter(1, $value)-&gt;getQuery()-&gt;execute();
      }
  
      public static function filterByDateTimeRange($column, DateTimeRange $dateTimeRange, QueryBuilder $queryBuilder = null)
      {
          if($queryBuilder == null)
              $queryBuilder = static::getPreBuiltQueryBuilder();
          if($dateTimeRange != null &amp;&amp; $dateTimeRange-&gt;start instanceof \DateTime &amp;&amp; $dateTimeRange-&gt;end instanceof \DateTime) {
              return $queryBuilder-&gt;andWhere(
              $queryBuilder-&gt;expr()-&gt;between($column, ':dateTimeFrom', ':dateTimeTo')
              )-&gt;setParameters(['dateTimeFrom' =&gt; $dateTimeRange-&gt;start, 'dateTimeTo' =&gt; $dateTimeRange-&gt;end]);
          }
          return $queryBuilder;
      }
  }
  </code></pre>
  
  <p><strong>DeviceRepository</strong></p>
  
  <pre><code>namespace Asterisk\DbBundle\Entity\Repositories;
  use AppBundle\Entity\ExtendedEntityRepository;
  
  /**
   * DeviceRepository
   *
   * This class was generated by the Doctrine ORM. Add your own custom
   * repository methods below.
   */
  class DeviceRepository extends ExtendedEntityRepository
  {
      //empty as it only needs to extend the ExtendedEntityRepository class
  }
  </code></pre>
  
  <p><strong>Extension</strong></p>
  
  <pre><code>namespace AppBundle\Wrappers;
  
  use Asterisk\DbBundle\Entity\Device;
  
  class Extension
  {
      public $displayName;
      public $number;
  
      public function __construct($number, $displayName = "")
      {
          $this-&gt;number = $number;
          $this-&gt;displayName = $displayName;
      }
  
      public static function createFromDevice(Device $device)
      {
          return new Extension($device-&gt;getUser(), $device-&gt;getDescription());
      }
  }
  </code></pre>
  
  <p><strong>Agent (This is an example of why having repositories access statically is helpful)</strong></p>
  
  <pre><code>namespace AppBundle\Wrappers;
  
  
  use AppBundle\Utils\DateTimeRange;
  use Asterisk\CdrDbBundle\Entity\Cdr;
  use Asterisk\CdrDbBundle\Entity\Repositories\CdrRepository;
  use Asterisk\DbBundle\Entity\Device;
  use Asterisk\DbBundle\Entity\Repositories\FeatureCodeRepository;
  use Asterisk\DbBundle\Entity\Repositories\QueueDetailRepository;
  use Asterisk\DbBundle\Enums\QueueDetailKeyword;
  
  class Agent
  {
      public $name;
  
      public $extension;
  
      /** @var  Call[] */
      public $calls = [];
  
      /** @var array|Queue[] */
      public $queues = [];
  
      /** @var AgentStats  */
      public $stats;
  
      private $_extension;
  
      public function __construct(Device $extension, DateTimeRange $dateTimeRange = null)
      {
          $this-&gt;_extension = $extension;
          $this-&gt;extension = Extension::createFromDevice($extension);
          $this-&gt;name = $this-&gt;extension-&gt;displayName;
          $this-&gt;calls = $this-&gt;getCalls($dateTimeRange);
          $this-&gt;stats = new AgentStats($this, $dateTimeRange);
      }
  
      public function getCalls(DateTimeRange $dateTimeRange = null)
      {
          /** @var CdrRepository $cdrRepo */
          $cdrRepo = CdrRepository::getPreBuiltQueryBuilder();
          $query = $cdrRepo-&gt;excludeNoAnswer($cdrRepo-&gt;filterByDateTimeRange($dateTimeRange));
  
          $cdrs = $query-&gt;andWhere(
                  $query-&gt;expr()-&gt;orX(
                      $query-&gt;expr()-&gt;eq('src', $this-&gt;extension-&gt;number),
                      $query-&gt;expr()-&gt;eq('dst', $this-&gt;extension-&gt;number)
                  )
              )-&gt;andWhere(
                  $query-&gt;expr()-&gt;notLike('dst', '*%')
              )
              -&gt;getQuery()-&gt;execute();
  
          foreach($cdrs as $cdr) {
              $this-&gt;calls[] = new Call($cdr);
          }
          return $this-&gt;calls;
      }
  
      public function getBusyRange(DateTimeRange $dateTimeRange = null)
      {
          $on = FeatureCodeRepository::getDndActivate();
          $off = FeatureCodeRepository::getDndDeactivate();
          $toggle = FeatureCodeRepository::getDndToggle();
  
          $query = CdrRepository::filterByDateTimeRange($dateTimeRange);
  
          /** @var Cdr[] $dndCdrs */
          $dndCdrs = $query-&gt;where(
                      $query-&gt;expr()-&gt;in('dst', [$on, $off, $toggle])
                  )
                  -&gt;where(
                      $query-&gt;expr()-&gt;eq('src', $this-&gt;extension-&gt;number)
                  )-&gt;getQuery()-&gt;execute();
  
          $totalTimeBusy = 0;
  
          /** @var \DateTime $lastMarkedBusy */
          $lastMarkedBusy = null;
          foreach($dndCdrs as $cdr) {
              switch($cdr-&gt;getDst())
              {
              case $on:
                  $lastMarkedBusy = $cdr-&gt;getDateTime();
                  break;
              case $off:
                  if($lastMarkedBusy != null)
                      $totalTimeBusy += $lastMarkedBusy-&gt;diff($cdr-&gt;getDateTime());
                  $lastMarkedBusy = null;
                  break;
              case $toggle:
                  if($lastMarkedBusy == null) {
                      $lastMarkedBusy = $cdr-&gt;getDateTime();
                  }
                  else
                  {
                      $totalTimeBusy += $lastMarkedBusy-&gt;diff($cdr-&gt;getDateTime());
                      $lastMarkedBusy = null;
                  }
                  break;
              }
          }
          return $totalTimeBusy;
      }
  
      public function getQueues()
      {
          $query = QueueDetailRepository::getPreBuiltQueryBuilder();
          $queues = $query-&gt;where(
                  $query-&gt;expr()-&gt;eq('keyword', QueueDetailKeyword::Member)
              )-&gt;where(
                  $query-&gt;expr()-&gt;like('data', 'Local/'.$this-&gt;extension-&gt;number.'%')
              )-&gt;getQuery()-&gt;execute();
  
          foreach($queues as $queue)
              $this-&gt;queues[] = Queue::createFromQueueConfig(QueueDetailRepository::findByColumn('extension', $queue-&gt;id), $queue);
          return $this-&gt;queues;
      }
  }
  </code></pre>
  
  <p><strong>EDIT 2:</strong></p>
  
  <p>Actually I forgot I declared each repository as a service, so I could omit the black magic voodoo in the <code>getInstance()</code> method. But loading the service on kernel event seems like a bad idea...</p>
  
  <pre><code>parameters:
      entity.device: Asterisk\DbBundle\Entity\Device
  services:
      asterisk.repository.device:
      class: Asterisk\DbBundle\Entity\Repositories\DeviceRepository
      factory: ["@doctrine.orm.asterisk_entity_manager", getRepository]
      arguments:
          - %entity.device%
      tags:
          - {name: kernel.event_listener, event: kernel.request, method: onKernelRequest}
  </code></pre>
  
  <p><strong>Edit 3</strong></p>
  
  <p><a href="https://stackoverflow.com/a/33135479/1443717">Cerad gave me an answer on my other related question</a> That suggested using a single kernel event listener service and injecting each repository as a dependency. Thus allowing me to access the repositories statically. My only concern is the overhead required to load each repository on every request. My ideal method would be lazy load the repositories, but I'm unaware of a method at this time. <a href="http://symfony.com/doc/current/components/dependency_injection/lazy_services.html" rel="nofollow noreferrer">proxy-manager-bridge</a> looked promising but with my singleton pattern I don't think it will work.</p>