Hgraca\MicroDI
, (*1)
, (*2)
A small dependency injection library that uses reflection and a service locator container, to instantiate and recursively resolve, instantiate and inject dependencies., (*3)
Installation
To install the library, run the command below and you will get the latest version:, (*4)
composer require hgraca/micro-di
Usage
Factories
The factories used in Builder::buildFromFactory
need to extend Hgraca\MicroDI\FactoryInterface
., (*5)
The method Builder::buildFromFactory
instantiates the factory and calls the create
method on it.
The arguments given to Builder::buildFromFactory
will be used both when instantiating the factory and when
calling the create
method:
* They will be injected in the __construct()
if the arguments keys match any of the dependencies names.
* They will all be injected in the create()
, together with whatever is in the container with the key
'.context', where is the relevant factory FQCN., (*6)
Dependency resolution process
The builder will resolve and instantiate dependencies. The dependencies, both when instantiating and when calling
a method with Builder::call
, will fe filled in the following priority:, (*7)
- By matching the dependencies names with the name of the provided arguments
- If its a class/interface, it will try to instantiate it, which in turn:
- tries to fetch it from the container, by searching for the class/interface fqcn as one of the containers keys
- If the key (class/interface fqcn) is found:
- If its an instance, it will be used (singleton)
- If its a closure, it will be used to instantiate the required class (singleton)
- If its a factory, it will be used to build the required class through the method
Builder::buildFromFactory
, and build a new instance every time (making it not a singleton)
- If the key (class/interface fqcn) is not found:
- If its a class it will be instantiated (recursively resolving and injecting its dependencies) and it
will be cached in the container
- If its an interface, an error will be thrown
- If its not a class/interface it will try to find the dependencies in the container, by their name.
- If it fails to find all mandatory dependencies, it will throw an error while instantiating the class.
Todo