I would like to create a number of entity query methods/functions that I can have easy access to from my entity handlers and controllers.
With Doctrine 2/Symfony 2 you can just attach such methods to the object/entity repository, and then you can call this repository from elsewhere in your code. Should I follow this recipe in D8, and if so, how?
I see 4 options for where to put the queries:
Put the methods in my custom entity class. However, out of the box the entity.query service doesn't seem to be available in
Drupal\Core\Entity\ContentEntityBase
, nor is the service container. I can use\Drupal::entityQuery('myentity')
in a method, but according to the documentation\Drupal::
should only be used in global functions. I suppose I can override the constructor and inject this class myself, but I would have thought this kind of functionality would be there already.Put the methods in my custom entity storage handler. However, if my understanding is correct, this is the place for special queries that aren't well handled by the entity query services.
Inject the querySelector wherever I need it. See \Drupal\node\Form\NodeTypeDeleteConfirm in Beta 9 for an example. This is not an appealing option.
Use global functions in my .module file. That way I can just use
\Drupal::entityQuery
and be done with it. See node.module for many sample implementations. However, this goes against the D8 documentation and against the goal of putting as much as possible into classes.
Any thoughts or references to emerging best practice would not go amiss :)