The way I handle Doctrine through Services, I do it like this:
Service->findAll() will look something like this:
public function findAll() { return $this->getEntityRepository()->findAll(); }
Now we need to define my_entity_service . I am doing this inside my Module.php
public function getServiceConfig() { return array( 'factories' => array( 'my_entity_service' => 'Namespace\Factory\MyServiceFactory' ) ); }
Next, I create Factory (note: this can also be done through an anonymous function inside the .php module)
<?php namespace Namespace\Factory; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\ServiceManager\FactoryInterface; use Namespace\Model\MyModel; class MyServiceFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $myModel= new MyModel(); $myModel->setEntityManager($serviceLocator->get('Doctrine\ORM\EntityManager')); return $myModel; } }
Now this is a lot to chew: D I fully understand this. What is happening here is actually very simple. Instead of creating your own model and somehow getting into the EntityManager, you call the ZF2 ServiceManager to create the Model for you and insert the EntityManager into it.
If this still bothers you, I will be happy to try to explain myself better. However, for further clarification, I would like to know about your use case. Ie: Why do you need EntityManager or where exactly do you need it.
This sample code is outside the scope of the questions.
Just to give you a live example of what I do through ServiceFactories with forms:
public function createService(ServiceLocatorInterface $serviceLocator) { $form = new ReferenzwertForm(); $form->setHydrator(new DoctrineEntity($serviceLocator->get('Doctrine\ORM\EntityManager'))) ->setObject(new Referenzwert()) ->setInputFilter(new ReferenzwertFilter()) ->setAttribute('method', 'post'); return $form; }
source share