PHP code example of romchik38 / php-container

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

    

romchik38 / php-container example snippets


$container = new \Romchik38\Container\Container();
$container->add('some key', 'any string');
$container->add('config', ['key' => 0]);
$container->add('important_object', new ImportantClass());
// somewhere in the code
$str = $container->get('some key');
// ...etc

$container = new \Romchik38\Container\Container();
$container->shared(
    '\Classes\Primitive1',                 // class name
    [7]                                    // params, number 7 in this case
);
// $shared1 and $shared2 are the same
$shared1 = $container->get('\Classes\Primitive1');
$shared2 = $container->get('\Classes\Primitive1');

$container = new \Romchik38\Container\Container();
$container->fresh(
    '\Classes\Primitive1',                  // class name
    [7]                                     // params, number 7 in this case
);
// $fresh1 and $fresh2 are defferent objects that hold the same number 7
$fresh1 = $container->get('\Classes\Primitive1');
$fresh2 = $container->get('\Classes\Primitive1');

// Interface example
$container = new \Romchik38\Container\Container();
$container->multi(
    '\DB\DatabaseUseSql',
    '\DatabaseInterface',
    true,                           // true - shared, false - fresh
    ['dsn:localhost']               // params
);

$database = $container->get('\DatabaseInterface');

$container = new \Romchik38\Container\Container();
$container->shared(
    '\DB\Database', 
    [
        'db:mysql',                         // first param as a string
        new Promise('\SomeConnection'),     // second param as a promise
    ]
);

$container->fresh(
    '\SomeConnection',     // class name
    []                     // params, in that case is nothing
);

$container = new \Romchik38\Container\Container();

$container->shared(
    '\ClassA1', 
    [new Promise('\ClassA2')]
);

$container->shared(
    '\ClassA2', 
    [new Promise('\ClassA1')]
);
// Exception there