# DI Container

GitHub

# Description

A PHP dependency injection container implementing the PSR-11 Container Interface.

Bind objects to the container and resolve them. Instantiate new objects and automatically resolve dependencies needed, to construct the object.

# Installation

# Composer

This package is installed via composer. Simply run composer require mrcrmn/container in your terminal. Don't forget to require composers generated autoloader.

# Basic Usage

First, you need to create a new container instance.

use mrcrmn\Container\Container;

$container = new Container();

# Binding objects to the container

To bind an object to the container, simply call the bind or set method. This method takes the id and the object.

$object = new Example();

$container->bind(Example::class, $object);

You may pass an optional third parameter to set an alias for this object.

$object = new Example();

$container->bind(Example::class, $object, 'example');

It is also possible to pass a closure which returns an object.

$container->bind(Example::class, function($container) {
    return new Example();
});

# Resolving objects from the container

To resolve an object from the container, simply call the resolve or get method.

$container->resolve(Example::class);

Or use the alias, if you set one.

$container->resolve('example');

# Creating instances

The most powerful feature if this container is the ability to create new objects by dynamically resolving the constructor dependencies out of the container.

For example:

class Example
{
    protected $dependency;

    public function __construct(Dependency $dependency)
    {
        $this->dependency = $dependency;
    }
}

$container = new Container();

// Bind the dependency to the container.
$container->bind(Dependency::class, new Dependency());

// Create the object just by passing the full qualified classname.
$container->make(Example::class);

If you want to call a method on an existing object, you may use the call and pass in the object and the method name.

The container will auto resolve all the necessary dependencies.

class Example
{
    public function doSomething(Dependency $dependency)
    {
        // ...
    }
}

$container = new Container();

// Bind the dependency to the container.
$container->bind(Dependency::class, new Dependency());

// Create the object.
$example = new Example();

// Call the method.
$container->call($example, 'doSomething');