mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-29 22:46:22 +00:00
60 lines
1.3 KiB
Markdown
60 lines
1.3 KiB
Markdown
---
|
||
id: 269a4976-5800-4914-b49e-4bf16dd64797
|
||
title: "@required"
|
||
---
|
||
|
||
# Description
|
||
|
||
When autowiring is enabled for a service, you can also configure the
|
||
container to call methods on your class when it’s instantiated. For
|
||
example, suppose you want to inject the `logger` service, and decide to
|
||
use setter-injection:
|
||
|
||
``` php
|
||
// src/Util/Rot13Transformer.php
|
||
namespace App\Util;
|
||
|
||
class Rot13Transformer
|
||
{
|
||
private $logger;
|
||
|
||
/**
|
||
* @required
|
||
*/
|
||
public function setLogger(LoggerInterface $logger)
|
||
{
|
||
$this->logger = $logger;
|
||
}
|
||
|
||
public function transform($value)
|
||
{
|
||
$this->logger->info('Transforming '.$value);
|
||
// ...
|
||
}
|
||
}
|
||
|
||
```
|
||
|
||
Autowiring will automatically call any method with the @required
|
||
annotation above it, autowiring each argument. If you need to manually
|
||
wire some of the arguments to a method, you can always explicitly
|
||
configure the method call.
|
||
|
||
Despite property injection has some drawbacks, autowiring with @required
|
||
annotation can also be applied to public typed properties:
|
||
|
||
``` php
|
||
namespace App\Util;
|
||
|
||
class Rot13Transformer
|
||
{
|
||
/** @required */
|
||
public LoggerInterface $logger;
|
||
|
||
public function transform($value)
|
||
{
|
||
$this->logger->info('Transforming '.$value);
|
||
// ...
|
||
}
|
||
}
|
||
```
|