PHP code example of mindplay / unbox

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


interface CacheInterface {
    // ...
}

class FileCache implements CacheInterface {
    public function __construct($path) { ... }
}

class UserRepository {
    public function __construct(CacheInterface $cache) { ... }
}

use mindplay\unbox\ContainerFactory;

$factory = new ContainerFactory();

// register a component named "cache":
$factory->register("cache", function ($cache_path) {
    return new FileCache($cache_path);
});

// register "CacheInterface" as a component referencing "cache":
$factory->alias(CacheInterface::class, "cache");

// register "UserRepository" as a component:
$factory->register(UserRepository::class);

$factory->set("cache_path", "/tmp/cache");

$container = $factory->createContainer();

$users = $container->get(UserRepository::class);

$container->call(function (UserRepository $users) {
    $users->...
});

class UserController
{
    public function __construct(UserRepository $users)
    {
        // ...
    }

    public function show($user_id, ViewEngine $view, FormHelper $form, ...)
    {
        // ...
    }
}

$controller = $container->create(UserController::class);

$container->call([$controller, "show"], $_GET);

register(string $type)                                 # register a component (for auto-creation)
register(string $type, array $map)                     # ... with custom constructor arguments
register(string $name, string $type)                   # ... with a specific name for auto-creation
register(string $name, string $type, array $map)       # ... and custom constructor arguments
register(string $name, callable $func)                 # ... with a custom creation function
register(string $name, callable $func, array $map)     # ... and custom arguments to that closure

set(string $name, mixed $value)                        # directly insert an existing component

add(ProviderInterface $provider)                       # register a configuration provider

alias(string $new_name, string $ref_name)              # make $ref_name available as $new_name

configure(callable $func)                              # manipulate a component upon creation
configure(callable $func, array $map)                  # ... with custom arguments to the closure
configure(string $name, callable $func)                # ... for a component with a specific name
configure(string $name, callable $func, array $map)    # ... with custom arguments

ref(string $name) : BoxedValueInterface                # create a boxed reference to a component

registerFallback(ContainerInterface $container)        # register a fallack container


get(string $name) : mixed                              # unbox a component
has(string $name) : bool                               # check if a component is defined/exists
isActive(string $name) : bool                          # check if a component has been unboxed

call(callable $func) : mixed                           # call any callable an inject arguments
call(callable $func, array $map) : mixed               # ... and override or add missing params

create(string $class_name) : mixed                     # invoke a constructor and auto-inject
create(string $class_name, array $map) : mixed         # ... and override or add missing params

use mindplay\unbox\ContainerFactory;

$factory = new ContainerFactory();

register(string $type)                                 # register a component (for auto-creation)
register(string $type, array $map)                     # ... with custom constructor arguments
register(string $name, string $type)                   # ... with a specific name for auto-creation
register(string $name, string $type, array $map)       # ... and custom constructor arguments
register(string $name, callable $func)                 # ... with a custom creation function
register(string $name, callable $func, array $map)     # ... and custom arguments to that closure

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

$factory->alias("db.cache", CacheInterface::class); // "db.cache" becomes an alias!

$container = $factory->createContainer();

var_dump($container->get("db.cache") === $container->get(CacheInterface::class)); // => bool(true)

$factory->set("db.host", "localhost");
$factory->set("db.port", "12345");

configure(callable $func)
configure(callable $func, array $map)
configure(string $name, callable $func)
configure(string $name, callable $func, array $map)

$factory->register(PDO::class, function ($db_host, $db_name, $db_user, $db_password) {
    $connection = "mysql:host={$db_host};dbname={$db_name}";

    return new PDO($connection, $db_user, $db_password);
});

$factory->configure(function (PDO $db) {
    $db->exec("SET NAMES utf8");
});

$factory->configure("logger.pdo", function (PDO $db) {
    $db->exec("SET NAMES utf8");
});

$factory->configure(function (Connection $db, LoggerInterface $logger) {
    $db->setLogger($logger);
});

$factory->set("app.middleware", function () {
    return [new RouterMiddleware, new NotFoundMiddleware];
);

$factory->configure("app.middleware", function ($middleware) {
    $middleware[] = new CacheMiddleware();

    return $middleware;
});

$factory->register(ProductRepository::class, function () { ... });

$factory->alias(ProductRepositoryInterface::class, ProductRepository::class);

$factory->configure(function (ProductRepositoryInterface $repo) {
    return new CachedProductRepository($repo);
});

class MyProvider implements ProviderInterface
{
    public function register(ContainerFactory $factory)
    {
        $factory->register(...);
        $factory->configure(...);
        // ...
    }
}

$factory->add(new MyProvider);
$factory->add(new TestDependenciesProvider);
$factory->add(new DevelopmentDebugProvider);
// ...

class MyProvider implements ProviderInterface
{
    public function register(ContainerFactory $factory)
    {
        $factory->

class MyProvider implements ProviderInterface
{
    public function register(ContainerFactory $factory)
    {
        $factory->

class MyPaymentProvider implements ProviderInterface
{
    public function register(ContainerFactory $factory)
    {
        $factory->provides("acme.payment-gateway");
        
        // ...
    }
}

$app_factory = new ContainerFactory();

// components we can reuse across many requests:

$app_factory->register(DatabaseConnection::class);

// factory for containers for individual requests:

$app_factory->register("request-context", function (ContainerInterface $app_container) {
    $request_container_factory = new ContainerFactory();

    // enable request-specific containers to look up long-lived services in the main container:

    $request_container_factory->registerFallback($app_container);

    return $request_container_factory;
});

// we can now register short-lived components against the `request-context` container factory:

$app_factory->configure("request-context", function (ContainerFactory $request_container_factory) {
    $request_container_factory->register(LoginController::class); // depends on DatabaseConnection
});

// now create the long-lived app container, e.g. in your "index.php" or CLI daemon script:

$app_container = $app_factory->createContainer();

$request_container = $app_container->get("request-context")->createContainer();

$controller = $request_container->get(LoginController::class);

$factory = new ContainerFactory();

// ... bootstrapping ...

$container = $factory->createContainer();

$cache = $container->get(CacheInterface::class);
$db_name = $container->get("db_name");

$container->call(function (CacheInterface $cache, $db_name) {
    // ...
});

$container->call(function (CacheInterface $cache, $name) {
    // ...
}, ["name" => $container->ref("db.name")]);

class Action
{
    public function __construct(Controller $controller, $action, array $params) { ... }
}

class ControllerFactory
{
    /** @var FactoryInterface */
    private $factory;

    public function __construct(FactoryInterface $factory) { ... }

    public function create($route, array $params)
    {
        list($controller_name, $action_name) = explode("/", $route);

        $controller_class = ucfirst($controller_name) . "Controller";

        $controller = $this->factory->create($controller_class);

        return new Action($controller, $action_name, $params);
    }
}

var_dump($container->has("foo")); // => bool(false)

$container->set("foo", "bar");

var_dump($container->has("foo")); // => bool(true)

$container->register("foo", function () { return "bar"; });

var_dump($container->isActive("foo")); // => bool(false)

$foo = $container->get("foo"); // component activates on first use

var_dump($container->isActive("foo")); // => bool(true)