-
Notifications
You must be signed in to change notification settings - Fork 0
Dependency Injection
Matěj Bucek edited this page Mar 16, 2021
·
2 revisions
There are many ways to define Service, Controller or Property.
Let's start with Attributes:
- Service Attribute
#[Service("ServiceName")]
class MyService{
...
}If you don't specify ServiceName, it will use default one. For this class it would be MyService.
- Controller Attribute
#[Controller("ControllerName")]
class MyController{
...
}The naming here works the same as with Services. That is because Controller is a Child of Service.
- Autowired Attribute
#[Autowired("@MyService")]
private MyService $service;
#[Autowired("%my.param%")]
private string $param;You can inject your Service or Parameter through Autowired attribute. You have to specify the name. @ symbol is used for Services and %% are used for Parameters.
You can use the dependency.yaml file to configure your Services and Parameters.
parameters:
my:
param: "Hello, world!"
services:
MyService:
class: App\MyService
arguments: ["%my.param%"]
SecondService:
class: App\SecondService
arguments: ["@MyService"]As you can see above, we can pass our arguments to the constructor like that:
class MyService{
public function __construct(string $param){
...
}
}class SecondService{
public function __construct(MyService $service){
...
}
}You cannot define Controller in the dependency.yaml file.
You should be careful to not to make circular dependency injection.