kodcube / dependency-injection
Dependency Injection Container
Requires
- php: >=7.0.0
- container-interop/container-interop: ~1.0
- psr/log: ~1.0
Requires (Dev)
- phpunit/phpunit: ~4.5
This package is not auto-updated.
Last update: 2024-12-21 20:08:47 UTC
README
This package is Recursive Dependency Injection Container (DiC) / Service Locator / Object Builder
It has been designed to take it's dependency configuration map as part of it's construction, so rather than setting up all the dependencies at runtime they can be loaded from a configuration file or files.
So as long as you can create an array, the configuration is injected at construction.
Main Features
- Build a Service/Object/Class based on a class name or alias
- Build a Class/Object that requires other dependencies
- Cache built Service/Object/Class for reuse in other classes (e.g. Database Connections)
- Build a Object/Class with a combination of passed and required dependencies
- Recursive Object Creation
Limitations
- Does not inject dependencies for methods other than __constructor
- Does not inject dependencies for setters
Requirements
-
PHP 7
-
container-interop/container-interop
-
Usage - Basic usage examples
Usage
Create Container
$di = new KodCube\DependencyInjection\Container(); or $di = new KodCube\DependencyInjection\Container($config); or $di = new KodCube\DependencyInjection\Container([ 'MyAlias' => 'Vendor\Package\Class', 'Vendor\Package\Interface' => 'Vendor\Package\Class' ])
Get Object from Container using an alias
Using Alias
$object = $di->get('MyAlias'); or $object = $di('MyAlias'); or $object = $di->MyAlias();
Using Class Name
$object = $di->get('Vendor\Package\Class'); or $object = $di('Vendor\Package\Class');
Using Interface Name (requires dependency map)
$object = $di->get('Vendor\Package\Interface'); or $object = $di('Vendor\Package\Interface');
Check if Alias\Class Exists in Container
Alias $object = $di->has('MyAlias'); Class $object = $di->has('Vendor\Package\Class');
Make Object
Make a object using the DiC using passed arguments.
This will also take advantage of the autowiring properties of the container.
Note: Objects created with additional arguments are not cached by the container.
$object = $di->make('Vendor\Package\Class','argument1','argument2');