Skip to content
Rougin Gutib edited this page Aug 15, 2017 · 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
{
    public function baz()
    {
        // ...
    }
}

class Bar
{
    protected $foo;

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

    public function booz()
    {
        return $this->foo->baz();
    }
}

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 Rougin\Slytherin\Container\Container;

$bar = $container->set('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 PSR-11 standard. Slytherin also have a sample implementation of it here.

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

$container = new Rougin\Slytherin\Container\Container;

// Define your classes and dependencies here...

(new Rougin\Slytherin\Application($container))->run();