Skip to content
Rougin Gutib edited this page Aug 23, 2016 · 23 revisions

A container resolves the dependencies of the specified class and inserts it to its container (list of instances) that can be used later.

In this example, let's create two classes like this:

class Foo
{
    // ... Code
}

class Bar
{
    protected $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }
}

In order for Bar to have an instance of Foo, we need to do this:

$foo = new Foo;
$bar = new Bar($foo);

But what if you want to declare a class with a dependency that needs also a dependency to it? You need to that thing above again and again, which is cumbersome for a developer. In order to fix that problem, we need to use a container to resolve dependencies to classes with ease.

// ... Given that Foo and Bar classes were included

$container = new Container;

$bar = $container->add('Bar');

That's the basic functionality of a container. Some libraries also provides more functionalities other than that. You can find a list of libraries that implement the dependency injection design pattern at awesome-php.

Example

To integrate a container to Slytherin, you will need to implement the component in Interop\ContainerInterface. I have also provided a sample implementation of a container here.

Depending on the package that you want to use, you will need to instantiate first your dependencies before adding it as the container component in Component\Collection.

$components = new Rougin\Slytherin\Component\Collection;
$container = new Rougin\Slytherin\IoC\Vanilla\Container;

// Instantiate your dependencies here...

$components->setContainer($container);