Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c10d923

Browse files
committed
feature #17933 [DependencyInjection] Autoconfigurable attributes (alexandre-daubois)
This PR was merged into the 5.4 branch. Discussion ---------- [DependencyInjection] Autoconfigurable attributes Fixes #15000 Commits ------- 4ba2bcc [DependencyInjection] Autoconfigurable attributes
2 parents 1a37dd9 + 4ba2bcc commit c10d923

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

service_container/tags.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,54 @@ In a Symfony bundle, call this method in the ``load()`` method of the
175175
}
176176
}
177177

178+
Autoconfiguration registering is not limited to interfaces. It is possible
179+
to use PHP 8 attributes to autoconfigure services by using the
180+
:method:`Symfony\\Component\\DependencyInjection\\ContainerBuilder::registerAttributeForAutoconfiguration`
181+
method::
182+
183+
// src/Attribute/SensitiveElement.php
184+
namespace App\Attribute;
185+
186+
#[\Attribute(\Attribute::TARGET_CLASS)]
187+
class SensitiveElement
188+
{
189+
private string $token;
190+
191+
public function __construct(string $token)
192+
{
193+
$this->token = $token;
194+
}
195+
196+
public function getToken(): string
197+
{
198+
return $this->token;
199+
}
200+
}
201+
202+
// src/Kernel.php
203+
use App\Attribute\SensitiveElement;
204+
205+
class Kernel extends BaseKernel
206+
{
207+
// ...
208+
209+
protected function build(ContainerBuilder $containerBuilder): void
210+
{
211+
// ...
212+
213+
$containerBuilder->registerAttributeForAutoconfiguration(SensitiveElement::class, static function (ChildDefinition $definition, SensitiveElement $attribute, \ReflectionClass $reflector): void {
214+
// Apply the 'app.sensitive_element' tag to all classes with SensitiveElement
215+
// attribute, and attach the token value to the tag
216+
$definition->addTag('app.sensitive_element', ['token' => $attribute->getToken()]);
217+
});
218+
}
219+
}
220+
221+
.. versionadded:: 5.3
222+
223+
The :method:`Symfony\\Component\\DependencyInjection\\ContainerBuilder::registerAttributeForAutoconfiguration`
224+
method was introduced in Symfony 5.3.
225+
178226
Creating custom Tags
179227
--------------------
180228

0 commit comments

Comments
 (0)