PHP-Easy-Container
, (*1)
An implement for singleton and some features., (*2)
Requirement
Installation
using composer:, (*3)
composer require johnroyer/php-easy-container
Simple Usage
Put whatever you want into container:, (*4)
use \Zeroplex\Container\Container;
$c = new Container;
// set value as singleton
$c['pi'] = 3.14159;
$c['db'] = new PDO(
'mysql:dbname=mydb;host=localhost',
'user',
'password'
);
Get things out from container:, (*5)
$c['pi']; // 3.14159
$c['db']; // object(PDO)
Singleton
If you use ArrayAccess interfaces to access the data from container, container will treat them as sinleton, as example ablove., (*6)
You can also use method singleton() to put data into container:, (*7)
$c->singleton('db') = new PDO(
'mysql:dbname=mydb;host=localhost',
'user',
'password'
);
$c->get('db'); // object(PDO)
You can also put a global variable into container:, (*8)
$c->singleton('config') = new Config(
APP_ROOT . '/config'
);
$c['config']['app.name'];
Late initialize
Sometimes, you are not sure if an DB connection should initialize while program start up. Maybe connect to DB when it is really needed is a better idea., (*9)
Use a Closure to let container known you want to initialize it later:, (*10)
$c['db'] = function () {
return new PDO(
'mysql:dbname=test;host=localhost',
'user',
'password'
);
};
$c->get('db'); // new PDO if and only if someone get it
// object(PDO)
Provide
Container can contains things with states, can also contains things stateless. provide() method stores bussiness logic or workflow which is stateless., (*11)
$c->provide('pi', 3.14159265359);
$c['pi']; // 3.14159265359
$c->provide('nowDate', function() {
// always return special format of date
return (new DateTime())
->format('Y-m-d');
});
$c->['nowDate']; // "2017-12-01"