Skip to content

A lightweight PHP dependency injection container.

Notifications You must be signed in to change notification settings

flashytime/container

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Container

A lightweight PHP dependency injection container.

Installation

composer require flashytime/container

Usage

Create a container
use Flashytime\Container\Container;
$container = new Container();
Register a closure
$this->container->set('hello', function () {
    return 'Hello World!';
});
echo $this->container->get('hello'); //Hello World!
$this->container->set('name', function () {
    return 'Mocha';
});
$this->container->set('mocha', function ($container) {
    return sprintf('Hello %s!', $container->get('name'));
});
echo $this->container->get('mocha'); //Hello Mocha!
Register a instance or class
$this->container->set('foo', function () {
    return new Foo();
});

or

$this->container->set('foo', new Foo());

or

$this->container->set('foo', 'Flashytime\Container\Tests\Foo');

or

$this->container->set('foo', Flashytime\Container\Tests\Foo::class);
Get the entry
$this->container->get('foo');
Register a singleton
$this->container->setSingleton('foo', Flashytime\Container\Tests\Foo::class);
$first = $this->container->get('foo');
$second = $this->container->get('foo');
var_dump($first === $second); //true
Dependency Injection
interface FooInterface
{

}

class Foo implements FooInterface
{
    private $name;
    private $age;

    public function __construct($name = null, $age = 0)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

    public function getAge()
    {
        return $this->age;
    }
}

class Bar
{
    public $foo;

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

    public function getFoo()
    {
        return $this->foo;
    }
}
$this->container->set(FooInterface::class, Foo::class);
$this->container->set('bar', Bar::class);
$bar = $this->container->get('bar');
var_dump($bar instanceof Bar); //true
var_dump($bar->getFoo() instanceof Foo); //true

see tests to get more usages.

License

MIT

About

A lightweight PHP dependency injection container.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages