Service Providers
What is bootstrapping?
It means registering things, including
Check out all providers at config/app.php. There are a lot of providers present in app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider\
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Laravel\Socialite\SocialiteServiceProvider::class,
],
Refer This for more understanding
Many of them are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.
Every service on Laravel register inside service container via the service provider
Every service container class has two methods
1) register
2) boot
Register Method
Boot Method
How to bind our declaration?
a) Use an inbuild service provider
At App\Providers\AppServiceProvider.php
We need to add a register or boot method
class AppServiceProvider extends ServiceProvider
{
public function register()
{
app()->bind('Puneet',function(){
return Str::random();
});
}
public function boot()
{
//
}
}
b) Creating your own service provider
step 1: You can create your service provider at App\Providers\
TestServiceProvide.php
or
php artisan make: provide TestServiceProvide
Step 3: Decelare this service provider at config/app.php
App\Providers\TestServiceProvide::class,
step 2
Then add binding at register or boot method
Singleton:
Decalare singleton instead of bind
app()->singleton('Puneet',function(){
return Str::random();
});
Refer
https://laravel.com/docs/8.x/providers
https://www.youtube.com/watch?v=1AxQNDOJTBw
https://www.youtube.com/watch?v=PGVqkEZiUoc
https://www.youtube.com/watch?v=_z9nzEUgro4
https://www.youtube.com/watch?v=GqVdt6OWN-Y
https://www.youtube.com/watch?v=yg1qOom6YuE