|
| 1 | +--- |
| 2 | +name: autowire |
| 3 | +description: Automatically bind and configure interfaces to class implementations. |
| 4 | +--- |
| 5 | + |
| 6 | +# Autowire |
| 7 | + |
| 8 | +## When to use this skill |
| 9 | +When an interface needs to be bound to a class one of these ways: |
| 10 | +```php |
| 11 | +$this->app->bind(HelloInterface::class, WorldClass::class); |
| 12 | +``` |
| 13 | +```php |
| 14 | +$this->app->when(Greeting::class)->needs(GoodbyeInterface::class)->give(GoodbyeInterface::class); |
| 15 | +``` |
| 16 | +```php |
| 17 | +$this->app->when(Greeting::class)->needs(GoodbyeInterface::class)->giveTagged(GoodbyeInterface::class); |
| 18 | +``` |
| 19 | +```php |
| 20 | +$this->app->when(Greeting::class)->needs(HelloInterface::class)->giveTagged('myTag'); |
| 21 | +``` |
| 22 | + |
| 23 | +It MUST be replaced with the usage of the following PHP Attributes: |
| 24 | +- `JeroenG\Autowire\Attribute\Autowire` |
| 25 | +- `JeroenG\Autowire\Attribute\Configure` |
| 26 | + |
| 27 | +## Examples |
| 28 | + |
| 29 | +### Autowiring interface to class |
| 30 | +```php |
| 31 | +use JeroenG\Autowire\Attribute\Autowire; |
| 32 | + |
| 33 | +#[Autowire] |
| 34 | +interface HelloInterface |
| 35 | +{ |
| 36 | +public function hello(): string; |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +### Configuring constructor arguments |
| 41 | +```php |
| 42 | +use JeroenG\Autowire\Attribute\Configure; |
| 43 | + |
| 44 | +// Will get the value set in config/app.php |
| 45 | +#[Configure(['$message' => '%app.message%'])] |
| 46 | + |
| 47 | +// Will inject an instance of the Message class |
| 48 | +#[Configure(['$message' => '@App\Domain\Message'])] |
| 49 | + |
| 50 | +// When you want tagged classes |
| 51 | +#[Configure(['$messages' => '#messages'])] |
| 52 | + |
| 53 | +// When you have multiple constructor arguments |
| 54 | +#[Configure(['$message' => '%app.message%', '$logger' => '@Psr\Log\LoggerInterface'])] |
| 55 | +class WorldClass |
| 56 | +{ |
| 57 | + private $message; |
| 58 | + private $logger; |
| 59 | + |
| 60 | + public function __construct($message, $logger) |
| 61 | + { |
| 62 | + $this->message = $message; |
| 63 | + $this->logger = $logger; |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +### Tagging an interface |
| 69 | +Use this only when there are multiple implementations of the same interface. |
| 70 | +```php |
| 71 | +use JeroenG\Autowire\Attribute\Tag; |
| 72 | + |
| 73 | +#[Tag] |
| 74 | +interface GoodbyeInterface |
| 75 | +{ |
| 76 | + public function goodbye(): string; |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +### Autowiring event listeners |
| 81 | +```php |
| 82 | +use JeroenG\Autowire\Attribute\Listen; |
| 83 | + |
| 84 | +#[Listen(Registered::class)] |
| 85 | +#[Listen(Login::class)] |
| 86 | +class UpdateLastLoginListener { |
| 87 | +} |
| 88 | +``` |
0 commit comments