How to Manage Common Dependencies with Parent Services

How to Manage Common Dependencies with Parent Services

As you add more functionality to your application, you may well start to have related classes that share some of the same dependencies. For example, you may have multiple repository classes which need the doctrine.orm.entity_manager service and an optional logger service:

  1. // src/Repository/BaseDoctrineRepository.php
  2. namespace App\Repository;
  3. use Doctrine\Persistence\ObjectManager;
  4. use Psr\Log\LoggerInterface;
  5. // ...
  6. abstract class BaseDoctrineRepository
  7. {
  8. protected $objectManager;
  9. protected $logger;
  10. public function __construct(ObjectManager $objectManager)
  11. {
  12. $this->objectManager = $objectManager;
  13. }
  14. public function setLogger(LoggerInterface $logger): void
  15. {
  16. $this->logger = $logger;
  17. }
  18. // ...
  19. }

Your child service classes may look like this:

  1. // src/Repository/DoctrineUserRepository.php
  2. namespace App\Repository;
  3. use App\Repository\BaseDoctrineRepository;
  4. // ...
  5. class DoctrineUserRepository extends BaseDoctrineRepository
  6. {
  7. // ...
  8. }
  9. // src/Repository/DoctrinePostRepository.php
  10. namespace App\Repository;
  11. use App\Repository\BaseDoctrineRepository;
  12. // ...
  13. class DoctrinePostRepository extends BaseDoctrineRepository
  14. {
  15. // ...
  16. }

The service container allows you to extend parent services in order to avoid duplicated service definitions:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Repository\BaseDoctrineRepository:
    4. abstract: true
    5. arguments: ['@doctrine.orm.entity_manager']
    6. calls:
    7. - setLogger: ['@logger']
    8. App\Repository\DoctrineUserRepository:
    9. # extend the App\Repository\BaseDoctrineRepository service
    10. parent: App\Repository\BaseDoctrineRepository
    11. App\Repository\DoctrinePostRepository:
    12. parent: App\Repository\BaseDoctrineRepository
    13. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Repository\BaseDoctrineRepository" abstract="true">
    9. <argument type="service" id="doctrine.orm.entity_manager"/>
    10. <call method="setLogger">
    11. <argument type="service" id="logger"/>
    12. </call>
    13. </service>
    14. <!-- extends the App\Repository\BaseDoctrineRepository service -->
    15. <service id="App\Repository\DoctrineUserRepository"
    16. parent="App\Repository\BaseDoctrineRepository"
    17. />
    18. <service id="App\Repository\DoctrinePostRepository"
    19. parent="App\Repository\BaseDoctrineRepository"
    20. />
    21. <!-- ... -->
    22. </services>
    23. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Repository\BaseDoctrineRepository;
    4. use App\Repository\DoctrinePostRepository;
    5. use App\Repository\DoctrineUserRepository;
    6. return function(ContainerConfigurator $configurator) {
    7. $services = $configurator->services();
    8. $services->set(BaseDoctrineRepository::class)
    9. ->abstract()
    10. ->args([ref('doctrine.orm.entity_manager')])
    11. ->call('setLogger', [ref('logger')])
    12. ;
    13. $services->set(DoctrineUserRepository::class)
    14. // extend the App\Repository\BaseDoctrineRepository service
    15. ->parent(BaseDoctrineRepository::class)
    16. ;
    17. $services->set(DoctrinePostRepository::class)
    18. ->parent(BaseDoctrineRepository::class)
    19. ;
    20. };

In this context, having a parent service implies that the arguments and method calls of the parent service should be used for the child services. Specifically, the EntityManager will be injected and setLogger() will be called when App\Repository\DoctrineUserRepository is instantiated.

All attributes on the parent service are shared with the child except for shared, abstract and tags. These are not inherited from the parent.

Note

If you have a _defaults section in your services.yaml file, all child services are required to explicitly override those values to avoid ambiguity. You will see a clear error message about this.

Tip

In the examples shown, the classes sharing the same configuration also extend from the same parent class in PHP. This isn’t necessary at all. You can also extract common parts of similar service definitions into a parent service without also extending a parent class in PHP.

Overriding Parent Dependencies

There may be times where you want to override what service is injected for one child service only. You can override most settings by specifying it in the child class:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Repository\DoctrineUserRepository:
    5. parent: App\Repository\BaseDoctrineRepository
    6. # overrides the private setting of the parent service
    7. public: true
    8. # appends the '@app.username_checker' argument to the parent
    9. # argument list
    10. arguments: ['@app.username_checker']
    11. App\Repository\DoctrinePostRepository:
    12. parent: App\Repository\BaseDoctrineRepository
    13. # overrides the first argument (using the special index_N key)
    14. arguments:
    15. index_0: '@doctrine.custom_entity_manager'
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... -->
    9. <!-- overrides the private setting of the parent service -->
    10. <service id="App\Repository\DoctrineUserRepository"
    11. parent="App\Repository\BaseDoctrineRepository"
    12. public="true"
    13. >
    14. <!-- appends the '@app.username_checker' argument to the parent
    15. argument list -->
    16. <argument type="service" id="app.username_checker"/>
    17. </service>
    18. <service id="App\Repository\DoctrinePostRepository"
    19. parent="App\Repository\BaseDoctrineRepository"
    20. >
    21. <!-- overrides the first argument (using the index attribute) -->
    22. <argument index="0" type="service" id="doctrine.custom_entity_manager"/>
    23. </service>
    24. <!-- ... -->
    25. </services>
    26. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Repository\BaseDoctrineRepository;
    4. use App\Repository\DoctrinePostRepository;
    5. use App\Repository\DoctrineUserRepository;
    6. // ...
    7. return function(ContainerConfigurator $configurator) {
    8. $services = $configurator->services();
    9. $services->set(BaseDoctrineRepository::class)
    10. // ...
    11. ;
    12. $services->set(DoctrineUserRepository::class)
    13. ->parent(BaseDoctrineRepository::class)
    14. // overrides the private setting of the parent service
    15. ->public()
    16. // appends the '@app.username_checker' argument to the parent
    17. // argument list
    18. ->args([ref('app.username_checker')])
    19. ;
    20. $services->set(DoctrinePostRepository::class)
    21. ->parent(BaseDoctrineRepository::class)
    22. # overrides the first argument
    23. ->arg(0, ref('doctrine.custom_entity_manager'))
    24. ;
    25. };

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.