PHP code example of rock-symphony / container

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

    

rock-symphony / container example snippets




use RockSymphony\ServiceContainer\ServiceContainer;

$container = new ServiceContainer();

// Definition:
// Set a service instance to container
$container->set('acme', new AcmeService());

// Consumer:
// Check if there is a service binding for given service ID  
echo $container->has('acme') ? 'It has acme service' : 'wtf?';

// Get a service from container
$acme = $container->get('acme');
$acme->doSomeStuff();


/** @var $container \RockSymphony\ServiceContainer\ServiceContainer */
// Definition:
// Note we bind instance by it's **abstract** interface.
// This way you force consumers to not care about implementation details, but rely on interface. 
$container->set(\Psr\Log\LoggerInterface::class, $my_fancy_psr_logger_implementation);

// Consumer:
// Then you have a consumer that needs a logger implementation,
// but doesn't care on details. It can use any PSR-compatible logger.
$logger = $container->get(\Psr\Log\LoggerInterface::class);
$logger->info('Nice!');


/** @var $container \RockSymphony\ServiceContainer\ServiceContainer */
// Definition:
$container->alias('logger', \Psr\Log\LoggerInterface::class);

// Consumer:
$logger = $container->get(\Psr\Log\LoggerInterface::class);
// ... or 
$logger = $container->get('logger'); // 100% equivalent
$logger->info('Nice!');


/** @var $container \RockSymphony\ServiceContainer\ServiceContainer */
// Definition:
$container->bindResolver('now', function () {
    return new DateTime();
});

// Consumer:
$now = $container->get('now'); // DateTime object
$another_now = $container->get('now'); // another DateTime object

echo $now === $another_now ? 'true' : 'false'; // == false


/** @var $container \RockSymphony\ServiceContainer\ServiceContainer */
// Definition:
$container->bindSingletonResolver('cache', function () {
    return new MemcacheCache('127.0.0.1');
});

// Consumer:
$cache = $container->get('cache'); // DateTime object
// do something with $cache


use RockSymphony\ServiceContainer\ServiceContainer;

/** @var $container ServiceContainer */
// Definition:
$container->deferred('cache', function () {
    return new MemcacheCache('127.0.0.1');
}); 

// Wrap cache service with logging decorator
$container->extend('cache', function($cache, ServiceContainer $container) { 
    // Note: it's passing a service container instance as second parameter
    //       so you can get dependencies from it.
    return new LoggingCacheDecorator($cache, $container->get('logger'));
});

// Consumer:
$cache = $container->get('cache'); // DateTime object
// Uses cache seamlessly as before
// (implying that MemcacheCache and LoggingCacheDecorator have the same interface)

$parent = new ServiceContainer();
$parent->set('configuration', $global_configuration);

$layer = new ServiceContainerLayer($existing_container);
$layer->set('configuration', $layer_configuration); 
$layer->bindResolver('layer_scope_service', ...);
// and so on

var_dump($parent->get('configuration') === $layer->get('configuration')); // "false"



// Class we need to inject dependencies into
class LoggingCacheDecorator {
    public function __construct(CacheInterface $cache, LoggerInterface $logger, array $options = []) {
        // initialize
    }
}

/** @var $container RockSymphony\ServiceContainer\ServiceContainer */
// Definition:
$container->set(LoggerInterface::class, $logger);
$container->set(CacheInterface::class, $cache);


// Consumer:
$logging_cache = $container->construct(LoggingCacheDecorator::class);
// you can also provide constructor arguments with second parameter:
$logging_cache = $container->construct(LoggingCacheDecorator::class, ['options' => ['level' => 'debug']]);


/** @var $container RockSymphony\ServiceContainer\ServiceContainer */

class MyController {
    public function showPost($url, PostsRepository $posts, TemplateEngine $templates)
    {
        // Warning! Pseudo-code :)
        $post = $posts->findPostByUrl($url);
        return $templates->render('post.html', ['post' => $post]); 
    }
    
    public static function error404(TemplateEngine $templates)
    {
        return $templates->render('404.html');
    }
}
// 1) It can auto-inject dependencies into instance method callables.
//    In this case it will check container for PostsRepository and TemplateEngine bindings.
//    Or try to create those instances automatically.
//    Or throw an exception if both options are not possible.
$container->call([$container, 'showPost'], ['url' => '/hello-world']);

// 2) It can construct class and auto-inject dependencies into method call:
//    Here it will first construct a new instance of MyController (see `->construct()`)
//    And then follows the same logic as the call 1) above.
$container->call('MyController@showPost', ['url' => '/hello-world']); 
// ... or the same: 
$container->call('MyController', ['url' => '/hello-world'], 'showPost');

// 3) It can auto-inject dependencies into static method call: 
$container->call(['MyController', 'error404']);
// ... or the same:
$container->call('MyController::error404');

// 4) It can auto-inject dependencies into closure function calls  
$container->call(function (PostsRepository $repository) {
    $repository->erase();
});