PHP code example of ronanchilvers / container

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

    

ronanchilvers / container example snippets


$container = new Container;
$container->set('my_service', function () {
    return new \My\Service();
});

$myService = $container->get('my_service');

$container = new Container;
$container->share('my_shared_service', function () {
    return new \My\Service();
});

$sharedService = $container->get('my_shared_service');

$container = new Container;
$container->set('settings', [
    'db' => [
        'adaptor'  => 'mysql',
        'username' => 'foobar',
        'password' => 'supersecret',
        'hostname' => '127.0.0.1'
    ]
]);
$container->set('my_string', 'foobar');

$settings = $container->get('settings');
$settings = $container->get('my_string');

$container = new Container;
$container->share('logger', function (){
    return new PSR11Logger();
});
$container->set('Psr\Log\LoggerInterface', '@logger');

// This:
$logger = $container->get('logger');
// returns the same instance as this:
$logger = $container->get('Psr\Log\LoggerInterface');

$container = new Container;
$container->share('my_service', function () {
    return new \My\Service;
});
$container->extend('my_service', function ($s, $c) {
    $s->registerWidget(new Widget);

    return $s;
});

$service = $container->get('my_service');

$container = new Container;
$container->set('logger', '\App\MyLogger');

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

use Psr\Log\LoggerInterface;

class MyLogger implements LoggerInterface
{
    ...
}
class MyService
{
    public function __construct(LoggerInterface $logger)
    {
        ...
    }
}
$container = new Container;
$container->share(LoggerInterface::class, 'MyLogger');
$container->share(MyService::class, 'MyService');

// This will return an instantiated service with the logger injected
$service = $container->get(MyService::class);

class ServiceProvider implements ServiceProviderInterface
{
    /**
     * @author Ronan Chilvers <[email protected]>
     */
    public function register(Container $container)
    {
        $container->set('my_service', function () {
            return new StdClass;
        });
    }
}

$container = new Container;
$container->register(new ServiceProvider);

$myService = $container->get('my_service');