Search code examples
phpeventsdoctrinedoctrine-ormdql

Event-based extension of query builder in Doctrine repository


I have a Doctrine entity Page which is loaded by module Foo. The page is a nested set provided by the Gedmo Doctrine Extension. The module Bar has another model Metadata, 1:1 related to a page. I would like to join the metadata directly when Foo loads the tree.

So inside module Foo:

$em->getRepository('My\Entity\Page')->getRootNodes();

This loads a collection of pages, but I'd like to have the metadata available directly. Because I trigger an event after loading the nodes, all modules can subscribe to this event and use the pages for whatever they want (in this case, meta data is required for a navigation structure, but navigation has nothing to do with module Foo, only with Bar).

The system must be kept modular, so Page has no dependency on Metadata. Is it somehow possible Bar listens to an event, building the query inside the repository? Then it adds an additional join to load the metadata of each page.

function getCalledOnEventTrigger($event)
{
    $q = $event->getQueryObject();
    $q->leftJoin('some join expression');
    // Query now joins metadata as well
}

Solution

  • I finished this by using the Zend\EventManager I inject into my custom repository. This works, but still doesn't work well because Doctrine must be aware of all relations, so the query I actually want to perform with the definitions in place, is impossible to execute. I solved it by adding the definitions nonetheless.