13
In frameworks Laravel 4 ou 5
and Symfony
, 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 in a container with their dependencies already solved, or else a Closure
, that loads the definitions of those dependencies (I think these are the "services"). Thus, by calling a particular service (which is in the container), we are calling in a more simplified way the instance of the desired class.
I will give an example of what I mean, but this example there is no Serviceprovider (service provider), but only the use of 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 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 an instance of Request
, we could do that:
$app->getService('url')->getRoot();
Service Provider
In the other case, we have the ServiceProvider
, which could do the following:
class UrlGeneratorProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('url', function ($app) { /** **/});
}
}
Then in that case, you’d be called by ServiceContainer
$app->setService(new UrlGeneratorProvider);
In that case, I understand that the UrlGeneratorProvider
, passes the definition necessary to create the service, simply through the method register
.
I found this pattern interesting and I’d like to know what their names are. Because in 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.