kodcube/dependency-injection

There is no license information available for the latest version (0.1.2) of this package.

Dependency Injection Container

0.1.2 2016-07-19 09:48 UTC

This package is not auto-updated.

Last update: 2024-04-13 16:12:58 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

Configuration 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');