From 6040cfe7258b2b33c3a95af0ccf37185fd9dff93 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Fri, 17 Mar 2023 13:11:53 +0100 Subject: [PATCH] [DependencyInjection] Add the `constructor` option to service definition --- service_container/factories.rst | 71 +++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/service_container/factories.rst b/service_container/factories.rst index 004846f48ec..0faa1f6b512 100644 --- a/service_container/factories.rst +++ b/service_container/factories.rst @@ -167,6 +167,77 @@ You can omit the class on the factory declaration: ->factory([null, 'create']); }; +It is also possible to use the ``constructor`` option, instead of passing ``null`` +as the factory class: + +.. configuration-block:: + + .. code-block:: php-attributes + + // src/Email/NewsletterManager.php + namespace App\Email; + + use Symfony\Component\DependencyInjection\Attribute\Autoconfigure; + + #[Autoconfigure(bind: ['$sender' => 'fabien@symfony.com'], constructor: 'create')] + class NewsletterManager + { + private string $sender; + + public static function create(string $sender): self + { + $newsletterManager = new self(); + $newsletterManager->sender = $sender; + // ... + + return $newsletterManager; + } + } + + .. code-block:: yaml + + # config/services.yaml + services: + # ... + + App\Email\NewsletterManager: + constructor: 'create' + arguments: + $sender: 'fabien@symfony.com' + + .. code-block:: xml + + + + + + + + + + + + .. code-block:: php + + // config/services.php + namespace Symfony\Component\DependencyInjection\Loader\Configurator; + + use App\Email\NewsletterManager; + + return function(ContainerConfigurator $containerConfigurator) { + $services = $containerConfigurator->services(); + + $services->set(NewsletterManager::class) + ->constructor('create'); + }; + +.. versionadded:: 6.3 + + The ``constructor`` option was introduced in Symfony 6.3. + Non-Static Factories --------------------