1
votes

Had a question about what best practice might be for the implementation of "convenience" queries. In reference to this article:

http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/#toc-install-doctrine-modules

It's clear that the entity manager is available in the IndexController - he does a findAll to list the entire contents of the database. What if, however, we added a "band" column to the database, mapped it out, and wanted to query all albums by the Beatles? What if the Beatles albums were used rather often throughout the codebase (weak example, but you get it).

The EM only seems to be available in Controllers, and Classes don't really seem to be aware of the service locator.

  • Would you simply break out DQL right in the controller, and repeat the DQL in every controller that needs it? (not very DRY)
  • Do we instead finagle some access to the EM from the Entity, or Model?

Doesn't seem as cut-and-dry as straight Zend_Db usage where you can fire queries anywhere you like, cheating to get things done.

Thanks for helping me cross over into a "real" ORM from the Table Gateway world.

1

1 Answers

2
votes

Erm, Doctrine 2 is able to handle Relationships (e.g.: Bands to Albums and vice-versa)

The EntityManager can be made available in every single class you wish, as long as you define the class as a service. I.e. inside your Module.php you can define a factory like this:

// Implement \Zend\ModuleManager\Feature\ServiceProviderInterface
public function getServiceConfig() {
    return array(
        //default stuff
        'factories' array(
            'my-album-service' = function($sm) {
                $service = new \My\Service\Album();
                $service->setEntityManager($sm->get('doctrine.entitymanager.orm_default'));
                return $service;
            }
        )
    )
);

You can then call this class from every Class that is aware of the ServiceManager like $this->getServiceLocator()->get('my-album-service')

This class would then automatically be injected with the Doctrine EntityManager.

To be clear: All queries you'd do SHOULD be located inside your Services. You'd have your Entities, which are basically the DB_Mapper from Doctrine 2, then you have your Services, which run actions like add(), edit(), findAll(), findCustomQuery(), etc...

You would then populate your Services with Data from the Controllers, the Service would give data back to the controller and the controller would pass said data to the view. Does that make sense to u and answer your question?