|
| 1 | +# Dependency Injection |
| 2 | + |
| 3 | +Dependency Injection is a design pattern used in software development to implement inversion of control or in simple |
| 4 | +terms is 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, |
| 7 | +setter injection, and property injection. |
| 8 | + |
| 9 | +DotKernel API, through it's |
| 10 | +[dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) package focuses only on constructor |
| 11 | +injection. |
| 12 | + |
| 13 | +## Usage |
| 14 | +DotKernel API comes out of the box with [dot-dependency-injection](https://github.com/dotkernel/dot-dependency-injection) |
| 15 | +package, which provide all we need for injecting dependencies in any object you want. |
| 16 | + |
| 17 | +`dot-dependency-injection` determines the dependencies by looking at the `#[Inject]` attribute, |
| 18 | +added to the constructor of a class. Dependencies are specified as separate parameters of the `#[Inject]` |
| 19 | +attribute. |
| 20 | + |
| 21 | +For our example we will inject a `UserService` and `config` dependencies in 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: `config.example` |
| 41 | +
|
| 42 | +After register the class in the `ConfigProvider`, under `factories`, using `Dot\DependencyInjection\Factory\AttributedServiceFactory::class` |
| 43 | + |
| 44 | +```php |
| 45 | +public function getDependencies(): array |
| 46 | +{ |
| 47 | + return [ |
| 48 | + 'factories' => [ |
| 49 | + UserHandler::class => AttributedServiceFactory::class |
| 50 | + ] |
| 51 | + ]; |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +That's it, by registering this, when your object will instantiate from the container, it will automatically resolve |
| 56 | +the dependencies needed for you object. |
| 57 | + |
| 58 | +>Dependencies injection applies to any object within DotKernel API, for example, you could inject dependencies in |
| 59 | +> a service and so on, just need to register it in the `ConfigProvider` |
0 commit comments