dariorieke / dependency-injection
A DependencyInjection Container implementing the PSR-11 Interface
This package is auto-updated.
Last update: 2024-11-29 06:02:59 UTC
README
A DependencyInjection Container implementing the PSR-11 Container Interface
Installation
install via composer
"require": {
"dariorieke/dependency-injection": "dev-master"
}
Running tests
run tests with the following command
./vendor/bin/phpunit .\tests
Usage
Registering a dependency
Dependencies are registered using functions which return the dependencies, they can be any callable
, which recieves the container as an argument. This allows you to inject dependencies from the container into other dependencies at creation. A normal dependency always returns a new instance of the class, in contrast to a singleton.
use DarioRieke\DependencyInjection\DependencyInjectionContainer;
$container = new DependencyInjectionContainer();
//register a queue
$container->register('queue', function ($container) {
return new SplQueue();
});
Registering a singleton
To register a singleton where the container always returns the same instance of the dependency, (a Logger
in this case):
use DarioRieke\DependencyInjection\DependencyInjectionContainer;
$container = new DependencyInjectionContainer();
$container->singleton('logger', function ($container) {
return new Logger();
});
Retrieving a dependency
Retrieving dependencies from the container is simple. Use the has
and get
methods to retrieve both singletons and normal dependencies
if($container->has('logger')) {
$logger = $container->get('logger');
}
Registering and retrieving Parameters
You can also register and retrieve parameters, for example configuration values
$container->setParameter('debug', true);
if($container->hasParameter('debug')) {
$debugMode = $container->getParameter('debug');
}
Adding method calls to dependenies
You may want to register a dependency and use a setter method to inject another dependency. This could be done inside the register function but you can do it in a more flexible way too. The addMethodCall
recieves an array of arguments for the method call
$container->addMethodCall('myDependency', 'setLogger', [ $container->get('logger') ]);
Dependency aliases
You can register dependencies with alias names, for example an Interface
name, and fetch it by its alias too.
$container->alias('logger', LoggerInterface::class);