PHP code example of flashytime / container

1. Go to this page and download the library: Download flashytime/container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

flashytime / container example snippets


use Flashytime\Container\Container;
$container = new Container();

$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!

$this->container->set('foo', function () {
    return new Foo();
});

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

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

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

$this->container->get('foo');

$this->container->setSingleton('foo', Flashytime\Container\Tests\Foo::class);
$first = $this->container->get('foo');
$second = $this->container->get('foo');
var_dump($first === $second); //true

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