velsym/dependency-injection

Dependency management system for PHP.

composer require velsym/dependency-injection

Velsym\DependencyInjection

DependencyManager

The heart of all instances.

Methods

  • loadDependencies(dependencies) - setup method to use dependencies.

    Returns: void

    Params:

    • dependencies - an array of dependencies (see DependencyBuilder on how to build own dependencies).

  • resolveClassToInstance(class, manualArguments[]) - returns fully instantiated object based on the given class.

    Returns: NULL|object

    Params:

    • class - class that will be resolved to an instance based on the dependency list given in loadDependencies method. 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 calls methodName on object with manualArguments[] and returns what the methodName returns.

    Returns: mixed

    Params:

    • object - object from which the methodName will 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

Setup
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. :D

Learn about DependencyBuilder to fully understand what's going on in How to use example.

How to use
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 21

Last updated