Support the ongoing development of Laravel.io →
posted 10 years ago
IOC
Last updated 2 years ago.
0

It depends. The automatic resolution approach is a little bit slower than the first approach (not something you have to worry about unless you have a big object graph) because the IoC container doesn't have to use a reflection class to inspect the constructor.

Last updated 2 years ago.
0
class FooServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('foo', function()
        {
            return new Foo(new Bar); // <----------
        });
    }

}
Last updated 2 years ago.
0

"It gives pretty much same result", not always because a class may need a dependency that is not bound to the container or it may need one that implements an interface.

For example the Illuminate\Events\Dispatcher can have a Illuminate\Container\Container as first argument or null as default, and if you use the automatic resolution it will create an instance of a Container to inject in the Dispatcher, and if you want to use an instance of Container that is already available you may use a closure to refer the dependencies to construct your instance.

The same happens to constructors that needs interfaces as dependencies, if you don't bind a class or an instance to an interface and you use automatic resolution to construct it the container will not resolve it. So again using a closure you can use the right dependencies.

Last updated 2 years ago.
0

You can also use the IoC container to inject construction parameters other than interfaces. For example:

class Foo
{

    protected $values = array();

    public function __construct(array $validValues)
    {
        $this->values = $validValues;
    }
}

Now, if you register this class with the Ioc Container:

$app->bind('Foo', function($app) {
    $valid = $app['config']->get('some.app.config', array());
    return new Foo($valid);
});

You can have the app inject Foo into other bound items without having to repeat that code:

class Bar
{
    public function __construct(Foo $foo) { }
}
App::make(Bar) \\automatically creates and injects Foo with the correct constructor arguments
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

YOzaz yozaz Joined 30 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.