johnroyer/php-easy-container

v1.1.1 2019-10-28 12:48 UTC

README

Build Status Coverage Status

An implement for singleton and some features.

Requirement

  • PHP >= 5.6

Installation

using composer:

composer require johnroyer/php-easy-container

Simple Usage

Put whatever you want into container:

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:

$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.

You can also use method singleton() to put data into container:

$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:

$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.

Use a Closure to let container known you want to initialize it later:

$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.

$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"