* // Register an instance as a singleton in the container
* IoC::instance('mailer', new Mailer);
*
*
* @param string $name
* @param mixed $instance
* @return void
*/
public static function instance($name, $instance)
{
static::$singletons[$name] = $instance;
}
/**
* Register a controller with the IoC container.
*
* @param string $name
* @param Closure $resolver
* @return void
*/
public static function controller($name, $resolver)
{
static::register("controller: {$name}", $resolver);
}
/**
* Resolve a core Laravel class from the container.
*
*
* // Resolve the "laravel.router" class from the container
* $input = IoC::core('router');
*
* // Equivalent resolution of the router using the "resolve" method
* $input = IoC::resolve('laravel.router');
*
*
* @param string $name
* @param array $parameters
* @return mixed
*/
public static function core($name, $parameters = array())
{
return static::resolve("laravel.{$name}", $parameters);
}
/**
* Resolve an object instance from the container.
*
*
* // Get an instance of the "mailer" object registered in the container
* $mailer = IoC::resolve('mailer');
*
* // Get an instance of the "mailer" object and pass parameters to the resolver
* $mailer = IoC::resolve('mailer', array('test'));
*
*
* @param string $name
* @param array $parameters
* @return mixed
*/
public static function resolve($name, $parameters = array())
{
if (array_key_exists($name, static::$singletons))
{
return static::$singletons[$name];
}
if ( ! static::registered($name))
{
throw new \Exception("Error resolving [$name]. No resolver has been registered.");
}
$object = call_user_func(static::$registry[$name]['resolver'], $parameters);
// If the resolver is registering as a singleton resolver, we will cache
// the instance of the object in the container so we can resolve it next
// time without having to instantiate a new instance of the object.
//
// This allows the developer to reuse objects that do not need to be
// instantiated each time they are needed, such as a SwiftMailer or
// Twig object that can be shared.
if (isset(static::$registry[$name]['singleton']))
{
return static::$singletons[$name] = $object;
}
return $object;
}
}