PHP code example of phpwatch / simple-container

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

    

phpwatch / simple-container example snippets



use Psr\Container\ContainerInterface;

$container = new PHPWatch\SimpleContainer\Container();  
  
$container['database.dsn'] = 'mysql:host=localhost;database=test';  
$container['database'] = static function(ContainerInterface $container): \PDO {  
 return new \PDO($container->get('database.dsn'));  
};
$container['api.ipgeo'] = 'rhkg3...';

  
$container['database']; // \PDO  
// OR  
$container->get('database'); // \PDO  
  

use Psr\Container\ContainerInterface;  
use PHPWatch\SimpleContainer\Container;  
  
$services = [  
    'database' => [
        'dsn' => 'sqlite...'  
    ],  
    'prefix' => 'Foo',  
    'csprng' => static function (ContainerInterface $container) {  
        return $container->get('prefix') . bin2hex(random_bytes(16));  
    }
]; 
  
$container = new Container($services);  
$container->get('prefix'); // Foo


$container->setFactory('http.client', static function(ContainerInterface $container) {
	$handler = new curl_init();
	curl_setopt($handler,CURLOPT_USERAGENT, $container->get('http.user-agent'));
	
	return $handler;
};


$container->setFactory('http.client'); // Mark existing definition as a factory.


$container['csprng'] = static function(): string {
	return bin2hex(random_bytes(32));
};

$container['csprng']; // "eaa3e95d4102..."
$container['csprng']; // "eaa3e95d4102..."
$container['csprng']; // "eaa3e95d4102..."


$container->setProtected('csprng', static function(): string {
	return bin2hex(random_bytes(32));
});

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

echo $csprng(); // eaa3e95d4102...
echo $csprng(); // b857ce87400b...
echo $csprng(); // a833e3db880...


// Remove:  
unset($container['secret.service']);  
  
// Extend:  
$container['secret.service'] = static function(): void { throw new \Exception('You are not allowed to use this');}