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

Skip to content

Commit 29ad979

Browse files
committed
feature #17696 [DependencyInjection] Add #[Target] documentation (alexandre-daubois)
This PR was merged into the 5.4 branch. Discussion ---------- [DependencyInjection] Add `#[Target]` documentation Closes #15261 Part of #17563 Commits ------- ce8739e [DependencyInjection] Add #[Target] documentation
2 parents 8e427e4 + ce8739e commit 29ad979

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

service_container/autowiring.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,36 @@ If the argument is named ``$shoutyTransformer``,
531531
But, you can also manually wire any *other* service by specifying the argument
532532
under the arguments key.
533533

534+
Another possibility is to use the ``#[Target]`` attribute. By using this attribute
535+
on the argument you want to autowire, you can define exactly which service to inject
536+
by using its alias. Thanks to this, you're able to have multiple services implementing
537+
the same interface and keep the argument name decorrelated of any implementation name
538+
(like shown in the example above).
539+
540+
Let's say you defined the ``app.uppercase_transformer`` alias for the
541+
``App\Util\UppercaseTransformer`` service. You would be able to use the ``#[Target]``
542+
attribute like this::
543+
544+
// src/Service/MastodonClient.php
545+
namespace App\Service;
546+
547+
use App\Util\TransformerInterface;
548+
use Symfony\Component\DependencyInjection\Attribute\Target;
549+
550+
class MastodonClient
551+
{
552+
private $transformer;
553+
554+
public function __construct(#[Target('app.uppercase_transformer')] TransformerInterface $transformer)
555+
{
556+
$this->transformer = $transformer;
557+
}
558+
}
559+
560+
.. versionadded:: 5.3
561+
562+
The ``#[Target]`` attribute was introduced in Symfony 5.3.
563+
534564
Fixing Non-Autowireable Arguments
535565
---------------------------------
536566

0 commit comments

Comments
 (0)