PHP code example of corviz / di-container

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

    

corviz / di-container example snippets


class A
{
    public funtion doSomething(){ /* ... */ }
    public function __construct() { echo "new instance of A"; }
}

class B
{
    public function __construct(A $a) { echo "new instance of B"; }
}

use Corviz\DI\Container;

$container = new Container();
$a = $container->get(A::class);

$a->doSomething(); //It works! :)

$b = $container->get(B::class);

//Outputs:
//new instance of A
//new instance of B

//Whenever this interface is met, the container will declare a class instance instead:
$container->set(AInterface::class, A::class);

//Declaring a constructor. This function will be called whenever 'B' class is met.
//Note: a closure is REQUIRED, in this case
$container->set(B::class, function (){
    $param1 = new A();
    
    return new B($param);
});

//Defining an instance. Whenever this interface is met, the same object will be accessed
$container->set(AInterface::class, new A());

$container->set('s3', new S3Client(/* ... */));

//...

$s3 = $container->get('s3');

$container->setSingleton(Queue::class, function(){
    $queue = new Queue();
    
    //setup...
    
    return $queue;
});

$queue = $container->get(Queue::class);
$queue->add(/* ... */);
echo $queue->count(); //1

//Somewhere else:

$queue = $container->get(Queue::class);
$queue->add(/* ... */);
echo $queue->count(); //2

class Person
{
    public function sayHello(string $name, string $surname = '')
    {
        echo "Hello $name $surname!";
    }
    
    public function sendMailMessage(PHPMailer $mail)
    {
        //send routine...
    }
}

$person = new Person();

// Inform only ound (auto wire)
$container->invoke($person, 'sendMailMessage');