1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Boot\Attribute; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Attribute for marking methods that provide a custom injector. |
9
|
|
|
* |
10
|
|
|
* Methods marked with this attribute will be used as injectors for the specified |
11
|
|
|
* alias type. An injector is responsible for creating and configuring instances |
12
|
|
|
* of a specific type when they're requested from the container. |
13
|
|
|
* |
14
|
|
|
* Unlike BindMethod and SingletonMethod which bind the return value of the method, |
15
|
|
|
* InjectorMethod binds the method itself as an injector for the specified type. |
16
|
|
|
* |
17
|
|
|
* Example usage: |
18
|
|
|
* ```php |
19
|
|
|
* class MyBootloader extends Bootloader |
20
|
|
|
* { |
21
|
|
|
* // Method will be used as injector for LoggerInterface |
22
|
|
|
* #[InjectorMethod(LoggerInterface::class)] |
23
|
|
|
* public function createLogger(string $channel = 'default'): LoggerInterface |
24
|
|
|
* { |
25
|
|
|
* return new Logger($channel); |
26
|
|
|
* } |
27
|
|
|
* |
28
|
|
|
* // Method will be used as injector for ConnectionInterface |
29
|
|
|
* #[InjectorMethod(ConnectionInterface::class)] |
30
|
|
|
* public function createDatabaseConnection(string $name = null): ConnectionInterface |
31
|
|
|
* { |
32
|
|
|
* return $name === null |
33
|
|
|
* ? new DefaultConnection() |
34
|
|
|
* : new NamedConnection($name); |
35
|
|
|
* } |
36
|
|
|
* } |
37
|
|
|
* ``` |
38
|
|
|
* |
39
|
|
|
* With the above example, any time a LoggerInterface is requested from the container, |
40
|
|
|
* the createLogger method will be called with any provided constructor arguments. |
41
|
|
|
* |
42
|
|
|
* Injectors are powerful for types that need custom creation logic or that |
43
|
|
|
* accept additional parameters during construction. |
44
|
|
|
* |
45
|
|
|
* @see BindMethod For simple method bindings |
46
|
|
|
* @see SingletonMethod For singleton method bindings |
47
|
|
|
*/ |
48
|
|
|
#[\Attribute(\Attribute::TARGET_METHOD)] |
49
|
|
|
final class InjectorMethod extends AbstractMethod |
50
|
|
|
{ |
51
|
|
|
/** |
52
|
|
|
* @param non-empty-string $alias The class or interface name to register this injector for. |
|
|
|
|
53
|
|
|
*/ |
54
|
4 |
|
public function __construct(string $alias) |
55
|
|
|
{ |
56
|
4 |
|
parent::__construct($alias); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|