简体   繁体   中英

How to get a list of services programmatically in Symfony?

I want to have a list of services and class names in my web application. I can use this command in console:

php bin/console debug:container

And I get something like this:

Symfony Container Public Services
=================================

 -------------------------------------------------------------------- --------------------------------------------------------------------------------------------
  Service ID                                                           Class name
 -------------------------------------------------------------------- --------------------------------------------------------------------------------------------
  annotation_reader                                                    Doctrine\Common\Annotations\CachedReader
  app.annotations.softdelete.driver                                    AppBundle\Doctrine\SoftDelete\Mapping\Driver\Annotation
  app.annotations.translate.driver                                     AppBundle\Doctrine\Mapping\Driver\TranslateDriver
  app.be_auth_controller.listener                                      AppBundle\EventListener\BeAuthControllerListener

I want to have this information on a web page using Symfony 3.

I created a service and I used:

$this->container->getServiceIds();

which returns something like:

[
  0 => "service_container"
  1 => "annotation_reader"
  2 => "annotations.reader"
  3 => "app.annotations.softdelete.driver"
  4 => "app.annotations.translate.driver"
...
]

I don't know, how to get the class names.

In any cases works this:

get_class($this->container->get($this->container->getServiceIds()[1]))

But in some other cases it throws different exceptions.

Your attempt with get_class is what came to mind as I was reading it, but whatever errors you are getting will come from improper fetching of those services. After all when you call $container->get(...) , its at that moment instantiating those classes.

To be honest the output you are looking to replicate can be reproduced based on the method used by that command.

https://github.com/symfony/framework-bundle/blob/master/Command/ContainerDebugCommand.php

You'll just need to adapt it to work for you.

To get full definition of given service you can use ContainerBuilder and Symfony cache file.

first create instance of ContainerBuilder:

$container = new ContainerBuilder();

then load cache file:

$cachedFile = $this->container->getParameter('debug.container.dump');
$loader = new XmlFileLoader($container, new FileLocator());
$loader->load($cachedFile);

now you can get full definition of your service like this:

$definition = $container->getDefinition('service_name')
$definition->getClass();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM