PHP code example of mpstyle / container

1. Go to this page and download the library: Download mpstyle/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/ */

    

mpstyle / container example snippets



interface Foo extends Injectable {}

class Dummy implements Injectable {}

class Bar implements Foo {
    public $dummy;

    public function __construct(Dummy $d){ $this->dummy = $d; }
}

$container = new Container();

// add an instance:
$container->addInstance(Foo::class, new Bar());

// or add a definition:
$container->addInstance(Foo::class, Bar::class);

// retrieve an object:
$foo =  $container->getInstance(Foo::class);

// $foo is an instance of Bar, and $dummy property of Bar is initialized as an instance of Dummy.


UniqueContainer::get()->addClosure( Foo::class, function ( Dummy $d ): Foo
{
    return new Bar( $d );
} );

/* @var $serviceB ServiceB */
$foo = UniqueContainer::get()->getInstance( Foo::class );

$path = 'definitions.ini';
$container = Container::fromIni($path);
$foo = $container->getInstance(Foo::class);

// $foo is an instance of Bar.



return [
    Foo::class => Bar::class
];

$path = 'definitions.php';
$container = Container::fromPHP($path);

$this->assertTrue($container->existsKey(Foo::class));

$foo = $container->getInstance(Foo::class);


interface Foo extends Injectable {}

class Dummy implements Injectable {}

class Bar implements Foo {
    public $dummy;

    public function __construct(Dummy $d){ $this->dummy = $d; }
}

// add an instance:
UniqueContainer::get()->addInstance( Foo::class, new Bar(new Dummy()) );

// or add a definition:
UniqueContainer::get()->addDefinition( Foo::class, Bar::class );

// retrieve an object:
$foo =  UniqueContainer::get()->getInstance(Foo::class);

// $foo is an instance of Bar, and $dummy property of Bar is initialized as an instance of Dummy.