Skip to content

Commit 6040cfe

Browse files
[DependencyInjection] Add the constructor option to service definition
1 parent 850e349 commit 6040cfe

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

service_container/factories.rst

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,77 @@ You can omit the class on the factory declaration:
167167
->factory([null, 'create']);
168168
};
169169
170+
It is also possible to use the ``constructor`` option, instead of passing ``null``
171+
as the factory class:
172+
173+
.. configuration-block::
174+
175+
.. code-block:: php-attributes
176+
177+
// src/Email/NewsletterManager.php
178+
namespace App\Email;
179+
180+
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
181+
182+
#[Autoconfigure(bind: ['$sender' => 'fabien@symfony.com'], constructor: 'create')]
183+
class NewsletterManager
184+
{
185+
private string $sender;
186+
187+
public static function create(string $sender): self
188+
{
189+
$newsletterManager = new self();
190+
$newsletterManager->sender = $sender;
191+
// ...
192+
193+
return $newsletterManager;
194+
}
195+
}
196+
197+
.. code-block:: yaml
198+
199+
# config/services.yaml
200+
services:
201+
# ...
202+
203+
App\Email\NewsletterManager:
204+
constructor: 'create'
205+
arguments:
206+
$sender: 'fabien@symfony.com'
207+
208+
.. code-block:: xml
209+
210+
<!-- config/services.xml -->
211+
<?xml version="1.0" encoding="UTF-8" ?>
212+
<container xmlns="http://symfony.com/schema/dic/services"
213+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
214+
xsi:schemaLocation="http://symfony.com/schema/dic/services
215+
https://symfony.com/schema/dic/services/services-1.0.xsd">
216+
217+
<services>
218+
<service id="App\Email\NewsletterManager" constructor="create">
219+
</service>
220+
</services>
221+
</container>
222+
223+
.. code-block:: php
224+
225+
// config/services.php
226+
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
227+
228+
use App\Email\NewsletterManager;
229+
230+
return function(ContainerConfigurator $containerConfigurator) {
231+
$services = $containerConfigurator->services();
232+
233+
$services->set(NewsletterManager::class)
234+
->constructor('create');
235+
};
236+
237+
.. versionadded:: 6.3
238+
239+
The ``constructor`` option was introduced in Symfony 6.3.
240+
170241
Non-Static Factories
171242
--------------------
172243

0 commit comments

Comments
 (0)