Skip to content

Commit 80c7eee

Browse files
committed
Merge branch '5.4' into 6.2
* 5.4: [DependencyInjection] Autoconfigurable attributes
2 parents 8978cd8 + c10d923 commit 80c7eee

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
@@ -171,6 +171,54 @@ In a Symfony bundle, call this method in the ``load()`` method of the
171171
}
172172
}
173173

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

0 commit comments

Comments
 (0)