In this case, the container will use a registered PHP callable to build new instances of a class. Each time when yii\di\Container::get()
is called, the corresponding callable will be invoked. The callable is responsible to resolve the dependencies and inject them appropriately to the newly created objects. For example :
$container->set('Foo', function ($container, $params, $config) {
$foo = new Foo(new Bar);
// ... other initializations ...
return $foo;
});
$foo = $container->get('Foo');
To hide the complex logic for building a new object, you may use a static class method as callable. For example :
class FooBuilder
{
public static function build($container, $params, $config)
{
$foo = new Foo(new Bar);
// ... other initializations ...
return $foo;
}
}
$container->set('Foo', ['app\helper\FooBuilder', 'build']);
$foo = $container->get('Foo');
By doing so, the person who wants to configure the Foo class no longer needs to be aware of how it is built.