In the Laravel 4 ou 5
and Symfony
frameworks, I realize that there are two classes that are essential for the operation of the whole system: ServiceContainer and ServiceProvider.
It seems to be a way for you to store instances of classes with their dependencies already resolved, or else a Closure
, which loads the definitions of these dependencies (I think these are the "services"). So, when calling a certain service (which is in the container), we are calling the instance of the desired class simpler.
I'm going to give you an example of what I'm trying to say, but there's no ServiceProvider (service provider), but only using the service container:
Service Container
class UrlGenerator
{
public function __construct(Request $request)
{}
}
class Request{
public function __construct(Header $header){}
}
class Header{}
Here comes the definition of the instances in the container.
$app->bind('header', function () {
return new Header;
});
$app->bind('request', function ($app)
{
return new Request($app->getService('header'));
});
$app->bind('url', function ($app)
{
return new UrlGenerator($app->getService('request'));
});
So if we needed to use the class UrlGenerator
, instead of always having to pass as an instance of Request
, we could do this:
$app->getService('url')->getRoot();
Service Provider
In the other case, we have ServiceProvider
, which could do the following:
class UrlGeneratorProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('url', function ($app) { /** **/});
}
}
Then in this case, it would be called by ServiceContainer
$app->setService(new UrlGeneratorProvider);
In this case, I understand that UrlGeneratorProvider
, passes the definition needed to create the service, simply through the register
method.
I found this pattern interesting and would like to know what their name is. For some frameworks the classes responsible for containing all services are called Application
, Container
or ServiceContainer
. In the case of "service providers" the names are always these, most of the time.