You are on page 1of 3

UnderstandserviceprovidersinLaravel

Thursday,June4th,2015byServage

ThesocalledserviceprovidersaretheheartbeatofyourLaravelapplication.Theyarethecentral
elementoftheinitializationprocesswherealltherelevantandrequiredcodeisloadedbyPHP.This
includesalltheessentialsfromtheframeworkitself,butalsoanyownandcustomcodeyouneedto
load.
Bootstrapserviceproviders
Duringtheinitializingprocessthecodebootstrapsitself.Thatmeansitgetsreadytogobyregistering
servicecontainerbignings,eventlisteners,middleware,configurationandroutes.Serviceproviders
arethereforeacentralplacetosetupyourapplication.Intheconfig/app.phpyouwillfindanarrayof
providerslistingalltheserviceproviderclassesthatareloadedduringbootstrapping.Bewarethat
manyoftheserviceproviderclassesmaybesocalleddeferredproviders.Itmeanstheyareonly
loadeduponrequest,andnotalwaysincludedbydefault.Makingaproviderdeferredworkswellfor
classesthatonlyneedtobeloadedsometimes,becauseitreducestheperformanceoverheadand
loadtimeofyourwebapplication.
Createacustomserviceprovider
Thecodebelowisanexampleofacustomserviceprovider.Itextendsthe
Illuminate\Support\ServiceProviderclasswhichisanabstractthatrequiresyoutodefineatleasta
methodcalledregister.Thepurposeoftheregistermethodistobindvaluesintheservice
container.
<?phpnamespaceApp\Providers;
useIlluminate\Support\ServiceProvider;
classMyServiceProviderextendsServiceProvider{
/**
*Registerbindingsinthecontainer.

*
*@returnvoid
*/
publicfunctionregister()
{

//Yourcode...

}
}
?>
Theservicecontainercanalsohaveamethodcalledbootwhichexecutesafterallserviceproviders
havebeenmadeavailable.Thereforeyoucanuseanyoftheotherserviceprovidersintheboot
method.Notebelowthatthebootmethodsupportstypehinteddependencyinjection.
<?phpnamespaceApp\Providers;
useEvent;
useIlluminate\Support\ServiceProvider;
classMyServiceProviderextendsServiceProvider{
/**
*Performpostregistrationbootingofservices.
*
*@returnvoid
*/
publicfunctionboot()
{

//Yourcode...

}
/**
*Registerbindingsinthecontainer.
*
*@returnvoid
*/
publicfunctionregister()
{

}
}

//Yourcode...

?>
Registeracustomserviceprovider
Nowthatyouhavecreatedacustomserviceprovider,youneedtoregisteritlikethedefault
frameworkcodeduringtheboostrappingprocess.Youcandosointheconfig/app.phpwhereyou
needtoaddyourcustomserviceprovidertothearraylikeintheexamplebelow:
'providers'=>[
//OtherServiceProviders
'App\Providers\MyServiceProvider',
],
Deferedserviceproviders
Previouslydeferredserviceproviderswerementionedtobeprovidersthatonlyloaduponrequest.
Youcanmakeyourserviceproviderdeferredbyaddingitasabooleanflagtotheserviceprovider
class.Thisavoidstheproviderloadingallbindingsfromthefilesystemandthusincreases
performance.
/**
*Indicatesifloadingoftheproviderisdeferred.
*
*@varbool
*/
protected$defer=true;
OverallserviceprovidersofferagoodwaytostructureandcentralizecodeinLaravel.Itoffersyoua
convenientwaytoprovideaspecificservicetoanymethodinyourcodebase.

You might also like