Skip to content

[DependencyInjection] Add the constructor option to service definition #18070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions service_container/factories.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

<!-- 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\Email\NewsletterManager" constructor="create">
</service>
</services>
</container>

.. 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
--------------------

Expand Down