|
| 1 | +# Dependency Injection |
| 2 | + |
| 3 | +Dependency injection is a design pattern used in software development to implement inversion of control. In simpler |
| 4 | +terms, it's the act of providing dependencies for an object during instantiation. |
| 5 | + |
| 6 | +In PHP, dependency injection can be implemented in various ways, including through constructor injection, setter |
| 7 | +injection and property injection. |
| 8 | + |
| 9 | +DotKernel API, through its [dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) package |
| 10 | +focuses only on constructor injection. |
| 11 | + |
| 12 | +## Usage |
| 13 | + |
| 14 | +**DotKernel API** comes out of the box with the |
| 15 | +[dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) package, which provides all we need for |
| 16 | +injecting dependencies into any object you want. |
| 17 | + |
| 18 | +`dot-dependency-injection` determines the dependencies by looking at the `#[Inject]` attribute, added to the constructor |
| 19 | +of a class. Dependencies are specified as separate parameters of the `#[Inject]` attribute. |
| 20 | + |
| 21 | +For our example we will inject `UserService` and `config` dependencies into a `UseHandler`. |
| 22 | + |
| 23 | +```php |
| 24 | +use Dot\DependencyInjection\Attribute\Inject; |
| 25 | + |
| 26 | +class UserHandler implements RequestHandlerInterface |
| 27 | +{ |
| 28 | + #[Inject( |
| 29 | + UserService::class, |
| 30 | + "config", |
| 31 | + )] |
| 32 | + public function __construct( |
| 33 | + protected UserServiceInterface $userService, |
| 34 | + protected array $config, |
| 35 | + ) { |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +> If your class needs the value of a specific configuration key, you can specify the path using dot notation: |
| 41 | +> `config.example` |
| 42 | +
|
| 43 | +The next step is to register the class in the `ConfigProvider` under `factories` using |
| 44 | +`Dot\DependencyInjection\Factory\AttributedServiceFactory::class` |
| 45 | + |
| 46 | +```php |
| 47 | +public function getDependencies(): array |
| 48 | +{ |
| 49 | + return [ |
| 50 | + 'factories' => [ |
| 51 | + UserHandler::class => AttributedServiceFactory::class |
| 52 | + ] |
| 53 | + ]; |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +That's it. When your object is instantiated from the container, it will automatically have its |
| 58 | +dependencies resolved. |
| 59 | + |
| 60 | +> Dependencies injection is available to any object within DotKernel API. For example, you can inject dependencies in a |
| 61 | +> service, a handler and so on, simply by registering it in the `ConfigProvider`. |
0 commit comments