Brain’s Container class IS the heart of the application. Anything added to the $core_cfg array in config/core.php is added to the container array through the class constructor. Container adds in all of the core class definitions, as well as any you define in app/config/container.php. Other fun stuff like session autostart, router initiation, and the closing of database connections are also done here.
Core Classes
Brain comes with a bunch of classes defined in a Pimple container. These definitions are located in config/container.php. In most instances, the definitions use Pimple’s share method, which means that the instance of the class is shared throughout the entire app, like a singleton.
Your App Classes
Go ahead and define your own classes in the container. Do this in app/config/container.php.
$this['foo'] = $this->share(function () use ($container) { return new \Foo( $container ); });
Notice how the container itself can be injected into the class. Now inside the Foo class, you’ll be able to use any of the classes that are defined in the container.
use \Brain\Lib\Container; class Foo { private $container; public function __construct( Container $container ) { $this->container = $container; } }
Container Access
If you create a static class that needs access to the container, simply extend ContainerAccess. The container is then available as parent::$container.
use \Brain\Lib\ContainerAccess; class StaticFoo extends ContainerAccess{ private static $instance = NULL; public static function get_instance() { if( is_null( self::$instance ) ) { self::$instance = parent::$container['foo']; } return self::$instance; } public static function __callStatic( $method, $params ) { $obj = self::get_instance(); return call_user_func_array( array( $obj, $method ), $params ); } }
With the optional __callStatic method usage shown in the above example, you can access methods of Foo through StaticFoo. If Foo has a method named bar, you could access it using StaticFoo::bar();.
Running From CLI
The Container class can tell if a request is from CLI or a standard HTTP request. The big difference in what happens when it figures it out is that CLI requests don’t have URIs, cookies, and input the way a HTTP request does. CLI usage therefore requires less in the way of core class instantiation, but remember that the classes are all available to you through the container.