Skip to content

Commit 963b4d6

Browse files
[DependnecyInjection] Add #[AutowireMethodOf] attribute to autowire a method of a service as a callable
1 parent b6d7264 commit 963b4d6

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\DependencyInjection\Attribute;
13+
14+
use Symfony\Component\DependencyInjection\Definition;
15+
use Symfony\Component\DependencyInjection\Reference;
16+
use Symfony\Component\DependencyInjection\TypedReference;
17+
18+
/**
19+
* Tells which method should be turned into a Closure based on the name of the parameter it's attached to.
20+
*/
21+
#[\Attribute(\Attribute::TARGET_PARAMETER)]
22+
class AutowireMethodOf extends AutowireCallable
23+
{
24+
/**
25+
* @param string $service The service containing the method to autowire
26+
* @param bool|class-string $lazy Whether to use lazy-loading for this argument
27+
*/
28+
public function __construct(string $service, bool|string $lazy = false)
29+
{
30+
parent::__construct($service, lazy: $lazy);
31+
}
32+
33+
public function buildDefinition(mixed $value, ?string $type, \ReflectionParameter $parameter): Definition
34+
{
35+
$value = class_exists($value) ? new TypedReference($value, $value) : new Reference($value);
36+
37+
return parent::buildDefinition([$value, $parameter->name], $type, $parameter);
38+
}
39+
}

src/Symfony/Component/DependencyInjection/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ CHANGELOG
88
* Add argument `$prepend` to `ContainerConfigurator::extension()` to prepend the configuration instead of appending it
99
* Have `ServiceLocator` implement `ServiceCollectionInterface`
1010
* Add `#[Lazy]` attribute as shortcut for `#[Autowire(lazy: [bool|string])]` and `#[Autoconfigure(lazy: [bool|string])]`
11+
* Add `#[AutowireMethodOf]` attribute to autowire a method of a service as a callable
1112

1213
7.0
1314
---

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy