1.1.8. Container Builder and Config Classes

The ContainerBuilder also builds fully-configured Container objects using ContainerConfig classes. It works using a two-stage configuration system.

The two stages are "define" and "modify". In the "define" stage, the ContainerConfig object defines constructor parameter values, setter method values, services, and so on. The ContainerBuilder then locks the Container so that these definitions cannot be changed, and begins the "modify" stage. In the "modify" stage, we may get() services from the Container and modify them programmatically if needed.

To build a fully-configured Container using the ContainerBuilder, we do something like the following:

use Aura\Di\ContainerBuilder;

$container_builder = new ContainerBuilder();

// use the builder to create and configure a container
// using an array of ContainerConfig classes
$di = $container_builder->newConfiguredInstance([
    'Aura\Cli\_Config\Common',
    'Aura\Router\_Config\Common',
    'Aura\Web\_Config\Common',
]);

A configuration class looks like the following:

namespace Vendor\Package;

use Aura\Di\Container;
use Aura\Di\ContainerConfig;

class Config extends ContainerConfig
{
    public function define(Container $di)
    {
        $di->set('log_service', $di->lazyNew('Logger'));
        $di->params['Logger']['dir'] = '/path/to/logs';
    }

    public function modify(Container $di)
    {
        $log = $di->get('log_service');
        $log->debug('Finished config.');
    }
}

Here are some example ContainerConfig classes from earlier Aura packages:

Alternatively, if you already have a ContainerConfig object created, you can pass it directly to the ContainerBuilder instead of a string class name:

$routerConfig = new Aura\Router\_Config\Common();

// use the builder to create and configure a container
// using an array of ContainerConfig classes
$di = $container_builder->newConfiguredInstance([
    'Aura\Cli\_Config\Common',
    $routerConfig,
    'Aura\Web\_Config\Common',
]);