Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9065265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:27:29+00:00 2026-06-16T16:27:29+00:00

How do I inject the service manager into a Doctrine repository to allow me

  • 0

How do I inject the service manager into a Doctrine repository to allow me to retrieve the Doctrine Entity Manager?

I using the ZF2-Commons DoctrineORMModule and are trying to implement the repository example listed in the Doctrine Tutorial (bottom of tutorial in link below):

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html

However, I keep getting a message “Fatal error: Call to a member function get() on a non-object in C:\zendProject\zf2 … “, which suggests that I do not have a working instance of the service locator.

My Doctrine repository looks like this:

namespace Calendar\Repository;

use  Doctrine\ORM\EntityRepository,
     Calendar\Entity\Appointment,
     Calendar\Entity\Diary;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ApptRepository extends EntityRepository implements ServiceLocatorAwareInterface 
{
   protected $services;

   public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
   {
       $this->services = $serviceLocator;
   }

   public function getServiceLocator()
   {
        return $this->services;
   }

  public function getUserApptsByDate()
  {
     $dql = "SELECT a FROM Appointment a";

     $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

     $query = $em()->createQuery($dql);

     return $query->getResult();
   }
}

I then want to call this in my controller using the following pattern:

$diary = $em->getRepository('Calendar\Entity\Appointment')->getUserApptsByDate();

EDIT: The attached link suggests that I may need to convert the class to a service,
https://stackoverflow.com/a/13508799/1325365

However, if this is the best route, how would I then make my Doctrine Entity aware of the service. At the moment I include an annotation in the doc block pointing to the class.

@ORM\Entity (repositoryClass="Calendar\Repository\ApptRepository") 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T16:27:30+00:00Added an answer on June 16, 2026 at 4:27 pm

    The way i approach things is this:

    First i register a Service for each entity. This is done inside Module.php

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'my-service-entityname' => 'My\Factory\EntitynameServiceFactory',
            )
        );
    }
    

    Next thing would be to create the factory class src\My\Factory\EntitynameServiceFactory.php. This is the part where you inject the EntityManager into your Entity-Services (not into the entity itself, the entity doesn’t need this dependency at all)

    This class looks something like this:

    <?php
    namespace My\Factory;
    
    use Zend\ServiceManager\ServiceLocatorInterface;
    use Zend\ServiceManager\FactoryInterface;
    use My\Service\EntitynameService;
    
    class EntitynameServiceFactory implements FactoryInterface
    {
        public function createService(ServiceLocatorInterface $serviceLocator)
        {
            $service = new EntitynameService();
            $service->setEntityManager($serviceLocator->get('Doctrine\ORM\EntityManager'));
            return $service;
        }
    }
    

    Next thing in line is to create the src\My\Service\EntitynameService.php. And this is actually the part where you create all the getter functions and stuff. Personally i extend these Services from a global DoctrineEntityService i will first give you the code for the EntitynameService now. All this does is to actually get the correct repository!

    <?php
    namespace My\Service;
    
    class EntitynameService extends DoctrineEntityService
    {
        public function getEntityRepository()
        {
            if (null === $this->entityRepository) {
                $this->setEntityRepository($this->getEntityManager()->getRepository('My\Entity\Entityname'));
            }
            return $this->entityRepository;
        }
    }
    

    This part until here should be quite easy to understand (i hope), but that’s not all too interesting yet. The magic is happening at the global DoctrineEntityService. And this is the code for that!

    <?php
    namespace My\Service;
    
    use Zend\EventManager\EventManagerAwareInterface;
    use Zend\EventManager\EventManagerInterface;
    use Zend\ServiceManager\ServiceManagerAwareInterface;
    use Zend\ServiceManager\ServiceManager;
    use Doctrine\ORM\EntityManager;
    use Doctrine\ORM\EntityRepository;
    
    class DoctrineEntityService implements
        ServiceManagerAwareInterface,
        EventManagerAwareInterface
    {
        protected $serviceManager;
        protected $eventManager;
        protected $entityManager;
        protected $entityRepository;
    
    
        /**
         * Returns all Entities
         *
         * @return EntityRepository
         */
        public function findAll()
        {
            $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, array('entities' => $entities));
            $entities = $this->getEntityRepository()->findAll();
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('entities' => $entities));
            return $entities;
        }
    
        public function find($id) {
            return $this->getEntityRepository()->find($id);
        }
    
        public function findByQuery(\Closure $query)
        {
            $queryBuilder = $this->getEntityRepository()->createQueryBuilder('entity');
            $currentQuery = call_user_func($query, $queryBuilder);
           // \Zend\Debug\Debug::dump($currentQuery->getQuery());
            return $currentQuery->getQuery()->getResult();
        }
    
        /**
         * Persists and Entity into the Repository
         *
         * @param Entity $entity
         * @return Entity
         */
        public function persist($entity)
        {
            $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, array('entity'=>$entity));
            $this->getEntityManager()->persist($entity);
            $this->getEntityManager()->flush();
            $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('entity'=>$entity));
    
            return $entity;
        }
    
        /**
         * @param \Doctrine\ORM\EntityRepository $entityRepository
         * @return \Haushaltportal\Service\DoctrineEntityService
         */
        public function setEntityRepository(EntityRepository $entityRepository)
        {
            $this->entityRepository = $entityRepository;
            return $this;
        }
    
        /**
         * @param EntityManager $entityManager
         * @return \Haushaltportal\Service\DoctrineEntityService
         */
        public function setEntityManager(EntityManager $entityManager)
        {
            $this->entityManager = $entityManager;
            return $this;
        }
    
        /**
         * @return EntityManager
         */
        public function getEntityManager()
        {
            return $this->entityManager;
        }
    
        /**
         * Inject an EventManager instance
         *
         * @param  EventManagerInterface $eventManager
         * @return \Haushaltportal\Service\DoctrineEntityService
         */
        public function setEventManager(EventManagerInterface $eventManager)
        {
            $this->eventManager = $eventManager;
            return $this;
        }
    
        /**
         * Retrieve the event manager
         * Lazy-loads an EventManager instance if none registered.
         *
         * @return EventManagerInterface
         */
        public function getEventManager()
        {
            return $this->eventManager;
        }
    
        /**
         * Set service manager
         *
         * @param ServiceManager $serviceManager
         * @return \Haushaltportal\Service\DoctrineEntityService
         */
        public function setServiceManager(ServiceManager $serviceManager)
        {
            $this->serviceManager = $serviceManager;
            return $this;
        }
    
        /**
         * Get service manager
         *
         * @return ServiceManager
         */
        public function getServiceManager()
        {
            return $this->serviceManager;
        }
    }
    

    So what does this do? This DoctrineEntityService pretty much is all what you globally need (to my current experience). It has the fincAll(), find($id) and the findByQuery($closure)

    Your next question (hopefully) would only be “How to use this from my controller now?”. It’s as simple as to call your Service, that you have set up in the first step! Assume this code in your Controllers

    public function someAction()
    {
        /** @var $entityService \my\Service\EntitynameService */
        $entityService = $this->getServiceLocator()->get('my-service-entityname');
    
        // A query that finds all stuff
        $allEntities = $entityService->findAll();
    
        // A query that finds an ID 
        $idEntity = $entityService->find(1);
    
        // A query that finds entities based on a Query
        $queryEntity = $entityService->findByQuery(function($queryBuilder){
            /** @var $queryBuilder\Doctrine\DBAL\Query\QueryBuilder */
            return $queryBuilder->orderBy('entity.somekey', 'ASC'); 
        });
    }
    

    The function findByQuery() would expect an closure. The $queryBuilder (or however you want to name that variable, you can choose) will be an instance of \Doctrine\DBAL\Query\QueryBuilder. This will always be tied to ONE Repository though! Therefore entity.somekey the entity. will be whatever repository you are currently working with.

    If you need access to the EntityManager you’d either only instantiate only the DoctrineEntityService or call the $entityService->getEntityManager() and continue from there.

    I don’t know if this approach is overly complex or something. When setting up a new Entity/EntityRepository, all you need to do is to add a new Factory and a new Service. Both of those are pretty much copy paste with two line change of code in each class.

    I hope this has answered your question and given you some insight of how work with ZF2 can be organized.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using FluentValidation and Ninject. I am trying to inject a service into
I have a service in which I inject the entity manager service (@doctrine.orm.entity_manager) because
I am trying to use Spring to inject @PersistenceContext entityManager into my service. The
I am trying to inject EJB into Spring (3.1.2) service (both in different WARs)
I'm using Ninject 3.0 to inject service layer data access classes into my controllers.
I'm trying to inject spring bean into JSF bean, I'm using Spring 3.1 and
Is is possible to inject IPrincipal using Castle Windsor into my asp.net mvc controller.
Is there any way to call service inside entity I need entity Manager inside
Is it possible to inject EJB 3.1 beans into POJO using CDI on Glassfish
I've created my own service and I need to inject doctrine EntityManager, but I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.