velsym/dependency-injection
Dependency management system for PHP.
composer require velsym/dependency-injectionVelsym\DependencyInjection
DependencyManager
The heart of all instances.
Methods
loadDependencies(dependencies)- setup method to use dependencies.Returns:
voidParams:
dependencies- an array of dependencies (see DependencyBuilder on how to build own dependencies).
resolveClassToInstance(class, manualArguments[])- returns fully instantiated object based on the givenclass.Returns:
NULL|objectParams:
class- class that will be resolved to an instance based on the dependency list given inloadDependenciesmethod. If class is not listed in the dependency list, it will try to construct class without using the dependency list.manualArguments[]- (optional) key-value array of constructor arguments for the given class (note that dependencies can have default values for constructor parameters, therefore you can overwrite them).
callMethodWithResolvedArguments(object, methodName, manualArguments[])- indirectly callsmethodNameonobjectwithmanualArguments[]and returns what themethodNamereturns.Returns:
mixedParams:
object- object from which themethodNamewill be called.methodName- name of the method that is meant to be called.manualArguments[]- (optional) key-value array of arguments for the method. Key is name of the method parameter.
getDependencies()- returns an array of loaded dependencies.Returns:
array
Examples
use Velsym\DependencyInjection\DependencyManager;
// required dependencies return an array.
$dependencies = [
// (require "dependencies.php"),
// (require "ext-dependencies.php"),
// (require "ext-dependencies-2.php")
];
// $dependencies is an array filled with an arrays of dependencies.
// loadDependencies method requires an array without any nested arrays.
// Meaning that all of the dependecies are on the same level/depth (0).
// Therefore we use (...) to unpack all elements of $dependecies.
// Then we merge them using array_merge and pass to loadDependencies.
DependencyManager::loadDependencies(array_merge(...$dependencies));
// Tada! DependencyManager is ready to use. :DLearn about DependencyBuilder to fully understand what's going on in How to use example.
use Velsym\DependencyInjection\DependencyManager;
class Person
{
public function __construct(string $name, int $age)
{
// ...
}
// ...
public function present(): string
{
return "My name is $this->name and I'm $this->age";
}
}
// Let's assume that Person is already mapped to Male::class (interface).
// Male::class has default arguments $name = "John" and $age = 21
// If we call resolveClassToInstance as such:
$person = DependencyManager::resolveClassToInstance(Male::class);
echo $person->present();
// Outputs: My name is John and I'm 21Last updated