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:

  1. 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.

  2. 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.

  3. Inject the querySelector wherever I need it. See \Drupal\node\Form\NodeTypeDeleteConfirm in Beta 9 for an example. This is not an appealing option.

  4. 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 :)

1 Answer 1


4 is definitely worse than 1. While \Drupal should be avoided to make unit testing and other things easier, it's still possible, but with calling functions, it's definitely not.

I fear there's no clear answer to this. There is no common standard for this in Drupal 8. A few modules have repository services, for example block.repository. You still have to manually inject that into your controllers, forms and other places, but you can make interfaces that are much easier to mock/test compared to an entity query.

  • Thanks. That is what I feared. Hopefully as the various APIs solidify there will be a more DX-friendly way of doing this. For now I will just use \Drupal and make a note to fix as D8 gets closer to release.
    – mesch
    Commented Apr 1, 2015 at 19:42
  • If you have ideas on specific improvements, based on what you know from Symfony/Doctrine, then you're more than welcome to create issues. Waiting and hoping usually doesn't help much i bringing things forward :) But there's not too much room for changing API's for 8.0.x, additions that improve DX might still be possible, though.
    – Berdir
    Commented Apr 1, 2015 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.