PHP code example of sergonie / container

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

    

sergonie / container example snippets



$serviceLocator = new Sergonie\Container\ServiceLocator();
$serviceLocator->set('my_awesome_service', new stdClass());

$myService = $serviceLocator->get('my_awesome_service');

var_dump($myService === $serviceLocator->get('my_awesome_service')); // returns true


use Sergonie\Container\ServiceLocator;

class Service 
{
    public $a;
    
    public function __construct(int $a = 1) 
    {
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->share(Service::class, function() { return new Service(2); });

var_dump($serviceLocator->get(Service::class)->a === 2); //true
var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // true


use Sergonie\Container\ServiceLocator;

class Service 
{
    public $a;
    
    public function __construct(int $a = 1) 
    {
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->factory(Service::class, function() { return new Service(2); });

var_dump($serviceLocator->get(Service::class)->a === 2); //true
var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // false


use Sergonie\Container\ServiceLocator;

class A
{
    
}

class Service 
{
    public $a;
    public $number;
    
    public function __construct(int $number = 7, A $a) 
    {
        $this->number = $number;
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->share(A::class);
$serviceLocator->share(Service::class);

var_dump($serviceLocator->get(Service::class)->a instanceof A);// true