1

Is there an easy (supported) way to programatically get all services in Drupal 8 that are tagged with a specific tag?

For example getting all services that are tagged with "breadcrumb_builder" tag

Example for a service tag from book module:

services:
  book.breadcrumb:
    class: Drupal\book\BookBreadcrumbBuilder
    arguments: ['@entity_type.manager', '@current_user']
    tags:
      - { name: breadcrumb_builder, priority: 701 }

Now if i want to get all services from all (enabled) *.services.yml files that are tagged with "breadcrumb_builder"?

I have seen and read this: https://symfony.com/doc/3.4/service_container/tags.html

But this seems to be really hard work and I am not sure if its even possible that way without touching Drupal core.

The Reference Tagged Services method looked very promising at first, but seems not to be supported from Drupal by default.

3
  • Can't you use the $container->findTaggedServiceIds('tag_name');?
    – user72672
    Commented Oct 16, 2019 at 15:14
  • You need to create a custom compiler pass, tags are only available at compile time
    – Clive
    Commented Oct 16, 2019 at 15:25
  • Or put your own service_collector service in the container which collects the tagged services at compile time. It's unclear what this question is about, but if you want to use the collected services for something this would be the way to go.
    – 4uk4
    Commented Oct 16, 2019 at 15:48

1 Answer 1

0

You need to implement a service collector to collect your tagged services there is a good explanation about this in the Collecting Services Drupal documentation

Take a look at this example:

# core.services.yml:
string_translation:
  class: Drupal\Core\StringTranslation\TranslationManager
  arguments: ['@language.default']
  tags:
    - { name: service_collector, tag: string_translator, call: addTranslator }

The service definition has a tag whose name is service_collector, which is how to tell Drupal that a service is a service collector. The tag attribute on the tag definition tells what tag name the collected services need to be tagged with in order to be collected; this can be omitted to use the collecting service's ID as the tag name.

The call attribute on the tag tells Drupal that the TranslationManager::addTranslator() method should be called once for each collected service that is located.

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.