0

I've recently started working with Drupal 8. I'm looking for a way to programatically(no drupal console or other CLI thing) get a list of all the services available.

Since it's built on top of Symfony I figured that the container should have a list of all the available services. Well, I was wrong.

I've searched around and I can't find any specific answers, other than the CLI option, which is not what I'm looking for.

If anybody can point me in the right direction here, I'd be grateful.

2
  • To be honest, command line in Drupal 8 is almost a requirement for any development.
    – Kevin
    Commented Feb 7, 2017 at 14:01
  • Agreed. But it this particular case it's not useful. I'm working a module that requires a full list of services. I haven't figured out a way(without using shell_exec or something of the sort) to get said list of services.
    – Andrew
    Commented Feb 7, 2017 at 14:10

2 Answers 2

3

You can get all services from the container by using the kernel method getCachedContainerDefinition():

$container = \Drupal::getContainer();
$kernel = $container->get('kernel');
$services = $kernel->getCachedContainerDefinition()['services'];
foreach ($services as $service_id => $value) {
  $service_definition = unserialize($value);
}

Now you can output a list, for example containing the service id and the class name in $service_definition['class'].

1
  • Perfect. Works like a charm.
    – Andrew
    Commented Feb 7, 2017 at 14:26
0

You can use tags for services and can get list of services with same tag like this. I didn't test this code, but there is a method findTaggedServiceIds.

services:
  process_text.text_filter:
    class: Drupal\process_text\TextFilterService
    tags:
      - { name: text_filter }

In your controller

//use Symfony\Component\DependencyInjection\ContainerBuilder;
public function process(ContainerBuilder $container) {
    $taggedServices = $container->findTaggedServiceIds('text_filter');
}
1
  • That's not really helping. What you wrote would imply knowing the alias for the service before hand, I don't know the aliases, hence I need a list of all services.
    – Andrew
    Commented Feb 7, 2017 at 14:14

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.