PHP code example of mindplay / boxy

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

    

mindplay / boxy example snippets


use mindplay\boxy\Container;

$container = new Container();

$container->insertService(new Database());

$container->registerService(
    Mapper::class,
    function (Database $db) {
        // type-hinted argument gets resolved and Database instance gets provided

        return new Mapper($db); // return type will be checked
    }
);

$container->invoke(function (Database $db, Mapper $mapper) {
    // type-hinted arguments are resolved - the Mapper and Database instance
    // are constructed as needed and provided for the consumer function.
});

$container->invoke(function (Optional $stuff = null) {
    if ($stuff) {
        // ...
    }
});

$container->registerComponent(
    ArticleFinder::class,
    function (Database $db) {
        return new ArticleFinder($db);
    }
);

$container->invoke(function (ArticleFinder $finder) {
    // a new ArticleFinder component is created every time you call invoke
});

$container->registerNamed('file_cache', CacheInterface::class, function () {
    return new FileCache(...);
});

$container->registerNamed('memory_cache', CacheInterface::class, function () {
    return new MemoryCache(...);
});

$container->invoke(function (CacheInterface $file_cache) {
    echo get_class($file_cache); // => FileCache
});

$container->invoke(function (CacheInterface $disk_cache) {
    echo get_class($disk_cache); // => DiskCache
});

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

$container->configure(function (Database $db) {
    $db->exec("set names utf8");
});

$container->overrideService(
    Database::class,
    function () {
        return new Database();
    }
);

use mindplay\boxy\Provider;

class ServiceProvider implements Provider
{
    public function register(Container $container)
    {
        $container->registerService(
            Database::class,
            function () {
                return new Database();
            }
        );
    }
}

$container->register(new ServiceProvider);

class PetStore implements Consumer
{
    protected $cat;
    protected $dog;
    
    public function getInjector()
    {
        return function (Cat $cat, Dog $dog) {
            $this->cat = $cat;
            $this->dog = $dog;
        };
    }
}

$container->provide($store = new PetStore);