All services are added to service container using Service Provider. Every service of your application is provided using service provider.

Lets open to bootstrap/app.php.We will see below code.

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

If we Ctrl+left mouse click on Application, class Application will open. Here Laravel is binding or registering serviceprovider

public function __construct($basePath = null)
{
    if ($basePath) {
        $this->setBasePath($basePath);
    }
    $this->registerBaseBindings();
    $this->registerBaseServiceProviders();
    $this->registerCoreContainerAliases();
}


Go to method registerConfiguredProviders() (from where getting all provider) and  dd(‘app.providers’) to see all provider that we are registering.

public function registerConfiguredProviders()
{
    dd('app.providers')
    $providers = Collection::make($this->make('config')->get('app.providers'))
                    ->partition(function ($provider) {
                        return strpos($provider, 'Illuminate\\') === 0;
                    });
    $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]);
    (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath()))
                ->load($providers->collapse()->toArray());
}

We will see all provider list

array:26 [

  0 => "Illuminate\Auth\AuthServiceProvider"

  1 => "Illuminate\Broadcasting\BroadcastServiceProvider"

  2 => "Illuminate\Bus\BusServiceProvider"

  3 => "Illuminate\Cache\CacheServiceProvider"

  4 => "Illuminate\Foundation\Providers\ConsoleSupportServiceProvider"

  5 => "Illuminate\Cookie\CookieServiceProvider"

  6 => "Illuminate\Database\DatabaseServiceProvider"

  7 => "Illuminate\Encryption\EncryptionServiceProvider"

  8 => "Illuminate\Filesystem\FilesystemServiceProvider"

  9 => "Illuminate\Foundation\Providers\FoundationServiceProvider"

  10 => "Illuminate\Hashing\HashServiceProvider"

  11 => "Illuminate\Mail\MailServiceProvider"

  12 => "Illuminate\Notifications\NotificationServiceProvider"

  13 => "Illuminate\Pagination\PaginationServiceProvider"

  14 => "Illuminate\Pipeline\PipelineServiceProvider"

  15 => "Illuminate\Queue\QueueServiceProvider"

  16 => "Illuminate\Redis\RedisServiceProvider"

  17 => "Illuminate\Auth\Passwords\PasswordResetServiceProvider"

  18 => "Illuminate\Session\SessionServiceProvider"

  19 => "Illuminate\Translation\TranslationServiceProvider"

  20 => "Illuminate\Validation\ValidationServiceProvider"

  21 => "Illuminate\View\ViewServiceProvider"

  22 => "App\Providers\AppServiceProvider"

  23 => "App\Providers\AuthServiceProvider"

  24 => "App\Providers\EventServiceProvider"

  25 => "App\Providers\RouteServiceProvider"

]

 

This service provider is coming form config/app.php Here we will see providers array and in provider we will see all service provider that are listed.

'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::class,
    Illuminate\Encryption\EncryptionServiceProvider::class,
    Illuminate\Filesystem\FilesystemServiceProvider::class,
    Illuminate\Foundation\Providers\FoundationServiceProvider::class,
    Illuminate\Hashing\HashServiceProvider::class,
    Illuminate\Mail\MailServiceProvider::class,
    Illuminate\Notifications\NotificationServiceProvider::class,
    Illuminate\Pagination\PaginationServiceProvider::class,
    Illuminate\Pipeline\PipelineServiceProvider::class,
    Illuminate\Queue\QueueServiceProvider::class,
    Illuminate\Redis\RedisServiceProvider::class,
    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
    Illuminate\Session\SessionServiceProvider::class,
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,

    /*
     * 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,

],

 

We know that if we want to bind something on container we can say

app()->bind('Hello',function (){
    return 'hi';
});

We are resolving Hello using make.

dd(app()->make('Hello'));

So its mean we are registering Hello class using binding. If we do not bind “Hello” it will show error like below

Target class [Hello] does not exist.

So the purpose of these is to use service provider to load it automatically. In our app’s service provider add this code

    public function register()
    {
        //
        $this->app->singleton(PaymentGateWay::class,function ($app){
            if (request()->has('credit')){
                return new CreditPaymentGateWay('usd');
            }

           return new BankPaymentGateWay('usd');

        });

        app()->bind('Hello',function (){
         return 'hi';
     });
    }

Now if we

dd(app());

we will see everything that your app is loaded. There are 27 service provider is loaded. But for this application some provider will not loaded until we call them such as CacheServiceProvider we see it implements DeferrableProvider. It means it will only load only when requested

class CacheServiceProvider extends ServiceProvider implements DeferrableProvider{

}

By Navid Anjum

Full-stack web developer and founder of Laravelaura. He makes his tutorials as simple as humanly possible and focuses on getting the students to the point where they can build projects independently. https://github.com/NavidAnjum

2 thoughts on “Laravel Service Providers”

Leave a Reply

Your email address will not be published. Required fields are marked *