runner/container

container for runner framework

v1.0.3 2020-05-15 15:29 UTC

This package is auto-updated.

Last update: 2024-03-16 00:28:20 UTC


README

A small IoC Container for PHP

68747470733a2f2f7472617669732d63692e6f72672f52756e6e65724c65652f636f6e7461696e65722e7376673f6272616e63683d6d6173746572 68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f52756e6e65724c65652f636f6e7461696e65722f6261646765732f636f7665726167652e706e673f623d6d6173746572 68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f52756e6e65724c65652f636f6e7461696e65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572 StyleCI 68747470733a2f2f706f7365722e707567782e6f72672f72756e6e65722f636f6e7461696e65722f762f737461626c65 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344372e302d3838393242462e737667 68747470733a2f2f706f7365722e707567782e6f72672f72756e6e65722f636f6e7461696e65722f6c6963656e7365

Installation

$ composer require runner/container

Usage

create an instance of the container, and bind services into the container with a name.

basic binding

use Runner\Container\Container;

$container = new Container();

$container->bind('stack', SplStack::class);

$container->make('stack');

$container->bind(ArrayAccess::class, function () {
    return new ArrayObject();
});

binding implementation

use an interface name as name and bind a concrete implementation to it

$container->bind(ArrayAccess::class, function () {
    return new ArrayObject();
});

$container->make(ArrayAccess::class);

binding singleton

$container->bind(
    'db', 
    function () {
        return new PDO();
    }, 
    true
);

$container->bind();

binding instance

just another way to binding singleton

$pdo = new PDO();

$container->instance('db', $pdo);

alias binding

bind an alias as concrete to a registered service

$container->bind(CacheInterface::class, function () {
    return new FileCache();
});

$container->bind('cache', CacheInterface::class, true);

$container->make('cache');

have fun :)

contextual binding

bind different implementation to classes while doing injecting

$container->bind(CacheInterface::class, function () {
    return new FileCache();
});

$container->bind('redis_cache', function () {
    return new RedisCache();
});

$container->bindContext(
    PageController::class,
    CacheInterface::class,
    function (Container $container) {
        return $container->make('redis_cache');
    }
);

$controller = $container->make(PageController::class);

References

License

MIT