Resolving Objects from the IoC Container


You have something stashed in the IoC container you want to retrieve.

You have a interface binding, an object, or even a piece of data in the IoC container and need to access it in your application.


Use App::make().

This is the complement App::bind().

// Somewhere in your code
App::bind('myclass', function($app)
    return new MyCoolClass();

// Later
$myclass = App::make('myclass');

It also complements App::instance().

// Somewhere in your code
App::instance('mydata', $mydata);

// Later
$mydata = App::make('mydata');

You can also retrieve singleton objects.

// Somewhere in your code
App::singleton('mysingleton', 'stdClass');

// Later
$var = App::make('mysingleton');
$var->test = '123';

// Even later
$var2 = App::make('mysingleton');
echo $var2->test;


App::make() is sort of a swiss-army knife of type resolution.

You can construct classes, resolving dependencies automatically.

class Foo {
class Bar {
    protected $foo;
    public function __construct(Foo $foo)
        $this->foo = $foo;

// Construct Bar, automatically injecting a Foo instance
$bar = App::make('Bar');

You can resolve interfaces which have been bound to the IoC container.

App::bind('SomeInterface', 'SomeClassImplementingSomeInterface');

$var = App::make('SomeInterface');

Also, you can use app() as an alias to App::make().

$obj = app('stdClass');
comments powered by Disqus