質問

I have a question about Laravel's IOC bindings, and especialy - ServiceProviders, who register Facade accessors.

Following official documentation for IOC

class FooServiceProvider extends ServiceProvider {

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

}

Where later on you can have a Facade, which just returns "foo" as "FacadeAccessor".

Wouldn't it be easier to rewrite this code like that?

class FooServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('foo', '\MyApp\Foo');
    }

}

It gives pretty much same result, as string will be wrapped into Closure automaticaly and parsed through App::make(). More than that - Foo constructor can have dependency injection if required (while you would have to pass exact objects in first case, and loose automatic resolution, as far as I understood).

Second option looks much cleaner, and unless you will need some additional logic before object initialization - like passing data, initializing other services/objects, etc. - looks better for me.

Maybe there are performance issues related to that? Or I am missing something else?

Interesting fact - in documentation, for Interfaces, Laravel suggests second option instead of Closure, but for ServiceProviders - direct object initialization.

役に立ちましたか?

解決

The second option is the best, closures are largely used to give a nice quick example of the way to do something.

Personally I avoid closures, with the exception of routes, as I like to have the option for the IoC container to run various different dependency injections should it be required.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top