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.
class FooServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('foo', function()
{
return new Foo(new Bar); // <----------
});
}
}
"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.
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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community