PHP code example of vpa / di

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

    

vpa / di example snippets




use VPA\DI\Container;
use VPA\DI\Injectable;

#[Injectable]
class A {

    function __construct() {}
    function echo () {
        print("\nThis is Sparta!\n");
    }
}

#[Injectable]
class B {

    function __construct(protected A $a) {}
    function echo () {
        $this->a->echo();
    }
}

class C {

    function __construct(protected A $a) {}
    function echo () {
        $this->a->echo();
    }
}

$di = new Container();
$di->registerContainers();
$b = $di->get(B::class); // returns instance of class B
$b->echo();
$c = $di->get(C::class); // returns exception (class C not tagged as Injectable)
$c->echo();

$di = new Container();
$di->registerContainers(['E'=>A::class]);
$e = $di->get('E');
echo $e instanceof A; // returns true

#[Injectable]
class A {
    function __construct() {}
}
#[Injectable]
class B {

    function __construct(protected A $a, private int $x, private int $y) {}
}

$di = new Container();
$di->registerContainers();
$b = $di->get(B::class,['x'=>10,'y'=>20]);