Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Service Container
  4. Service Locators
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Defining a Service Locator
  • Usage

Service Locators

Edit this page

Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

Service Locators

Sometimes, a service needs access to several other services without being sure that all of them will actually be used. In those cases, you may want the instantiation of the services to be lazy. However, that's not possible using the explicit dependency injection since services are not all meant to be lazy (see Lazy Services).

A real-world example are applications that implement the Command pattern using a CommandBus to map command handlers by Command class names and use them to handle their respective command when it is asked for:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/CommandBus.php
namespace AppBundle;

// ...
class CommandBus
{
    /**
     * @var CommandHandler[]
     */
    private $handlerMap;

    public function __construct(array $handlerMap)
    {
        $this->handlerMap = $handlerMap;
    }

    public function handle(Command $command)
    {
        $commandClass = get_class($command);

        if (!isset($this->handlerMap[$commandClass])) {
            return;
        }

        return $this->handlerMap[$commandClass]->handle($command);
    }
}

// ...
$commandBus->handle(new FooCommand());

Considering that only one command is handled at a time, instantiating all the other command handlers is unnecessary. A possible solution to lazy-load the handlers could be to inject the whole dependency injection container:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ...
use Symfony\Component\DependencyInjection\ContainerInterface;

class CommandBus
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function handle(Command $command)
    {
        $commandClass = get_class($command);

        if ($this->container->has($commandClass)) {
            $handler = $this->container->get($commandClass);

            return $handler->handle($command);
        }
    }
}

However, injecting the entire container is discouraged because it gives too broad access to existing services and it hides the actual dependencies of the services.

Service Locators are intended to solve this problem by giving access to a set of predefined services while instantiating them only when actually needed.

Defining a Service Locator

First, define a new service for the service locator. Use its arguments option to include as many services as needed to it and add the container.service_locator tag to turn it into a service locator:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
// app/config/services.yml
services:
    app.command_handler_locator:
        class: Symfony\Component\DependencyInjection\ServiceLocator
        tags: ['container.service_locator']
        arguments:
            -
                AppBundle\FooCommand: '@app.command_handler.foo'
                AppBundle\BarCommand: '@app.command_handler.bar'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- app/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="app.command_handler_locator" class="Symfony\Component\DependencyInjection\ServiceLocator">
            <argument type="collection">
                <argument key="AppBundle\FooCommand" type="service" id="app.command_handler.foo" />
                <argument key="AppBundle\BarCommand" type="service" id="app.command_handler.bar" />
            </argument>
            <tag name="container.service_locator" />
        </service>

    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// app/config/services.php
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\Reference;

//...

$container
    ->register('app.command_handler_locator', ServiceLocator::class)
    ->addTag('container.service_locator')
    ->setArguments(array(array(
        'AppBundle\FooCommand' => new Reference('app.command_handler.foo'),
        'AppBundle\BarCommand' => new Reference('app.command_handler.bar'),
    )))
;

Note

The services defined in the service locator argument must include keys, which later become their unique identifiers inside the locator.

Now you can use the service locator injecting it in any other service:

  • YAML
  • XML
  • PHP
1
2
3
4
// app/config/services.yml
services:
    AppBundle\CommandBus:
        arguments: ['@app.command_handler_locator']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- app/config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="AppBundle\CommandBus">
            <argument type="service" id="app.command_handler_locator" />
        </service>

    </services>
</container>
1
2
3
4
5
6
7
8
// app/config/services.php
use AppBundle\CommandBus;
use Symfony\Component\DependencyInjection\Reference;

$container
    ->register(CommandBus::class)
    ->setArguments(array(new Reference('app.command_handler_locator')))
;

Tip

If the service locator is not intended to be used by multiple services, it's better to create and inject it as an anonymous service.

Usage

Back to the previous CommandBus example, it looks like this when using the service locator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ...
use Psr\Container\ContainerInterface;

class CommandBus
{
    /**
     * @var ContainerInterface
     */
    private $handlerLocator;

    // ...

    public function handle(Command $command)
    {
        $commandClass = get_class($command);

        if (!$this->handlerLocator->has($commandClass)) {
            return;
        }

        $handler = $this->handlerLocator->get($commandClass);

        return $handler->handle($command);
    }
}

The injected service is an instance of ServiceLocator which implements the PSR-11 ContainerInterface, but it is also a callable:

1
2
3
4
5
// ...
$locateHandler = $this->handlerLocator;
$handler = $locateHandler($commandClass);

return $handler->handle($command);
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    No stress: we've got you covered with our 116 automated quality checks of your code

    No stress: we've got you covered with our 116 automated quality checks of your code

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Slaven, a Symfony contributor

    Thanks Slaven (@sbacelic) for being a Symfony contributor

    1 commit • 4 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia