@mac
To enable autowiring in Symfony, you need to follow these steps:
- Ensure that the framework.autowire configuration option is set to true in your config/services.yaml file. By default, Symfony enables autowiring, so you may not need to change anything here.
1
2
3
4
|
# config/services.yaml
services:
_defaults:
autowire: true
|
- In your class, where you want to use autowiring, add the @Route annotation to expose it as a service.
1
2
3
4
5
6
7
8
9
10
11
|
// src/Controller/ExampleController.php
use SymfonyComponentRoutingAnnotationRoute;
/**
* @Route("/example")
*/
class ExampleController
{
// ...
}
|
- Finally, you can use the autowiring feature in your controller or any other service class by type-hinting the required dependencies in the constructor or methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// src/Controller/ExampleController.php
use SymfonyComponentRoutingAnnotationRoute;
use AppServiceExampleService;
// ...
/**
* @Route("/example")
*/
class ExampleController
{
private $exampleService;
public function __construct(ExampleService $exampleService)
{
$this->exampleService = $exampleService;
}
// ...
}
|
That's it! Symfony will now automatically inject the required dependency (in this case ExampleService
) without the need for manually configuring it in the services.yaml file.