vincent15000's avatar

Are Service Containers a good idea to create modules ?

Hello,

Service Containers and Service Providers was very difficult to understand for me, so I decided to follow a tutorial and I found the Laracast series on Laravel 6 which contains some videos on Service Containers and Service Providers.

The concept is very well explained and in fact it's not so difficult to understand. And I even see some advantages to use them.

And now I wonder if Service Containers could be a good idea to create modules.

I explain what I mean by saying modules. In an application there can be several modules : users module, courses module, trainers module, tests module, ... and each module will have its own functionalities. The idea would be to encapsulate all business logic of a module in a Service Container so that it could be easily accessible from anywhere in the application when needed.

Is that a good idea ?

And what about performances ? I think that if you load more services when the application loads, it will take more time to load ?

Thanks for your suggestions ;).

V

0 likes
2 replies
martinbean's avatar
Level 80

@vincent15000 A service container is a central location where services are bound. An application should only have one container. You wouldn’t create “new” containers for a module; you’d instead have service providers in each module that adds that specific module’s services to the application’s service container.

As for performance, you can create “deferrable” service providers that only resolve services if they’re actually requested during a request:

class FooServiceProvider extends ServiceProvider implement DeferrableProvider
{
    public function register()
    {
        $this->app->singleton(FooService::class, function () {
            return new FooService();
        });
    }

    public function provides()
    {
        return [
            FooService::class,
        ];
    }
}

The provides method indicates what services the service provider actually provides. So the callback for the FooService will only be executed if FooService is actually requested.

1 like
vincent15000's avatar

@martinbean Ok thank you ... sorry I surely wanted to say service but I said container, I had understood that there is only one container but several services.

Thanks for the details, your answer reinforces my idea to use services for the different modules.

Hmmm ... perhaps one more question : is it possible to restrict the access to a specific service according to users' roles for example ?

Please or to participate in this conversation.