PHP code example of phetit / container

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

    

phetit / container example snippets


use Phetit\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();

$container->register('foo', fn() => 'bar');

$foo = $container->get('foo');
// $foo === 'bar'

$container->register('service', fn() => new Service());

$serviceOne = $container->get('service'); // Service object
$serviceTwo = $container->get('service'); // Service object

// $serviceOne === $serviceTwo => true

$container->factory('service', fn() => new Service());

$serviceOne = $container->get('service'); // Service object
$serviceTwo = $container->get('service'); // Service object

// $serviceOne === $serviceTwo => false

$container->parameter('foo', 'bar');
$container->parameter('closure', fn() => new Service());

$container->get('foo'); // 'bar'

// Parameters are not resolved
$closure = $container->get('closure'); // $closure = fn() => new Service()
$service = $closure(); // 'Service object'

$container->parameter('db_dns', 'mysql:dbname=testdb;host=127.0.0.1');
$container->parameter('db_user', 'dbuser');
$container->parameter('db_pass', 'dbpass');

$container->register('db', fn(Container $c) => new PDO(
    $c->get('db_dns'),
    $c->get('db_user'),
    $c->get('db_pass'),
));