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. How to Manage Common Dependencies with Parent Services
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
  • Overriding Parent Dependencies

How to Manage Common Dependencies with Parent Services

Edit this page

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Repository/BaseDoctrineRepository.php
namespace App\Repository;

use Doctrine\Persistence\ObjectManager;
use Psr\Log\LoggerInterface;

// ...
abstract class BaseDoctrineRepository
{
    protected $objectManager;
    protected $logger;

    public function __construct(ObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;
    }

    public function setLogger(LoggerInterface $logger): void
    {
        $this->logger = $logger;
    }

    // ...
}

Your child service classes may look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Repository/DoctrineUserRepository.php
namespace App\Repository;

use App\Repository\BaseDoctrineRepository;

// ...
class DoctrineUserRepository extends BaseDoctrineRepository
{
    // ...
}

// src/Repository/DoctrinePostRepository.php
namespace App\Repository;

use App\Repository\BaseDoctrineRepository;

// ...
class DoctrinePostRepository extends BaseDoctrineRepository
{
    // ...
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# config/services.yaml
services:
    App\Repository\BaseDoctrineRepository:
        abstract:  true
        arguments: ['@doctrine.orm.entity_manager']
        calls:
            - setLogger: ['@logger']

    App\Repository\DoctrineUserRepository:
        # extend the App\Repository\BaseDoctrineRepository service
        parent: App\Repository\BaseDoctrineRepository

    App\Repository\DoctrinePostRepository:
        parent: App\Repository\BaseDoctrineRepository

    # ...
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
<!-- 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
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="App\Repository\BaseDoctrineRepository" abstract="true">
            <argument type="service" id="doctrine.orm.entity_manager"/>

            <call method="setLogger">
                <argument type="service" id="logger"/>
            </call>
        </service>

        <!-- extends the App\Repository\BaseDoctrineRepository service -->
        <service id="App\Repository\DoctrineUserRepository"
            parent="App\Repository\BaseDoctrineRepository"
        />

        <service id="App\Repository\DoctrinePostRepository"
            parent="App\Repository\BaseDoctrineRepository"
        />

        <!-- ... -->
    </services>
</container>
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
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Repository\BaseDoctrineRepository;
use App\Repository\DoctrinePostRepository;
use App\Repository\DoctrineUserRepository;

return function(ContainerConfigurator $containerConfigurator) {
    $services = $containerConfigurator->services();

    $services->set(BaseDoctrineRepository::class)
        ->abstract()
        ->args([service('doctrine.orm.entity_manager')])
        // In versions earlier to Symfony 5.1 the service() function was called ref()
        ->call('setLogger', [service('logger')])
    ;

    $services->set(DoctrineUserRepository::class)
        // extend the App\Repository\BaseDoctrineRepository service
        ->parent(BaseDoctrineRepository::class)
    ;

    $services->set(DoctrinePostRepository::class)
        ->parent(BaseDoctrineRepository::class)
    ;
};

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.

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# config/services.yaml
services:
    # ...

    App\Repository\DoctrineUserRepository:
        parent: App\Repository\BaseDoctrineRepository

        # overrides the private setting of the parent service
        public: true

        # appends the '@app.username_checker' argument to the parent
        # argument list
        arguments: ['@app.username_checker']

    App\Repository\DoctrinePostRepository:
        parent: App\Repository\BaseDoctrineRepository

        # overrides the first argument (using the special index_N key)
        arguments:
            index_0: '@doctrine.custom_entity_manager'
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
<!-- 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
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!-- ... -->

        <!-- overrides the private setting of the parent service -->
        <service id="App\Repository\DoctrineUserRepository"
            parent="App\Repository\BaseDoctrineRepository"
            public="true"
        >
            <!-- appends the '@app.username_checker' argument to the parent
                 argument list -->
            <argument type="service" id="app.username_checker"/>
        </service>

        <service id="App\Repository\DoctrinePostRepository"
            parent="App\Repository\BaseDoctrineRepository"
        >
            <!-- overrides the first argument (using the index attribute) -->
            <argument index="0" type="service" id="doctrine.custom_entity_manager"/>
        </service>

        <!-- ... -->
    </services>
</container>
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
31
32
33
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Repository\BaseDoctrineRepository;
use App\Repository\DoctrinePostRepository;
use App\Repository\DoctrineUserRepository;
// ...

return function(ContainerConfigurator $containerConfigurator) {
    $services = $containerConfigurator->services();

    $services->set(BaseDoctrineRepository::class)
        // ...
    ;

    $services->set(DoctrineUserRepository::class)
        ->parent(BaseDoctrineRepository::class)

        // overrides the private setting of the parent service
        ->public()

        // appends the '@app.username_checker' argument to the parent
        // argument list
        ->args([service('app.username_checker')])
    ;

    $services->set(DoctrinePostRepository::class)
        ->parent(BaseDoctrineRepository::class)

        # overrides the first argument
        ->arg(0, service('doctrine.custom_entity_manager'))
    ;
};
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:

    Symfony 5.4 is backed by

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Symfony footer

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

    Avatar of Josip Kruslin, a Symfony contributor

    Thanks Josip Kruslin (@jkruslin) for being a Symfony contributor

    5 commits • 645 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