renanbr/sack

Minimal container implementation

dev-master 2016-02-11 18:12 UTC

This package is auto-updated.

Last update: 2020-10-05 09:39:47 UTC


README

Build Status

Sack is a minimal PHP container in compliance with Container Interoperability.

class RenanBr\Sack implements Interop\Container\ContainerInterface
{
    public function __construct(Interop\Container\ContainerInterface $fallback = null);

    public function set(string $key, mixed $value): void;

    public function get(string $key): mixed;

    public function has(string $key): bool;
}

Install

composer require renanbr/sack

Usage

Basics

$container = new RenanBr\Sack;

// raw values
$container->set('foo', 'bar');
$container->set('zoo', new MyClass);

// lazy and shared
$container->set('slow', function () {
    return new LazyClass;
});

// alias
$container->set('alias', function ($c) {
    return $c->get('original');
});

// storing a callable
$container->set('func', function () {
    return function () { /* ... */ };
});

Lazy, shared and serialized

Once callable isn't serializable, you may move the object creation to a static method. It's a good practice, even you don't need to deal with serialize entries.

$source = [
    'foo' => [Foo\Factory::class, 'staticPublicFactoryMethod'],
    'bar' => [Bar\Factory::class, 'staticPublicFactoryMethod'],
];
$config = unserialize(serialize($source));

$container = new RenanBr\Sack;
foreach ($config as $name => $value) {
    $container->set($name, $value);
}

Delegate lookup (or fallback)

Sack implements delegate lookup feature from Container Interoperability standards. To profit this feature, send a ContainerInterface to the Sack constructor.

$myContainer = new RenanBr\Sack($thirdContainer);

// will try get it from $thirdContainer
$myContainer->get('foo');