Skip to content

Dependency Injection

Matěj Bucek edited this page Mar 16, 2021 · 2 revisions

Dependency Injection

There are many ways to define Service, Controller or Property.

Attributes

Let's start with Attributes:

  1. Service Attribute
#[Service("ServiceName")]
class MyService{
  ...
}

If you don't specify ServiceName, it will use default one. For this class it would be MyService.

  1. Controller Attribute
#[Controller("ControllerName")]
class MyController{
  ...
}

The naming here works the same as with Services. That is because Controller is a Child of Service.

  1. 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.

Dependency file

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"]

Inject dependency through constructor

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){
      ...
   }
}

Warning

You cannot define Controller in the dependency.yaml file.

You should be careful to not to make circular dependency injection.

Clone this wiki locally