Laravel Service Providers

Laravel Service Providers

<?php

namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection(config('riak'));
        });
    }
}
  • Are the central place of all Laravel application bootstrapping.
  • Are the central place to configure your application.
  • Extend the Illuminate\Support\ServiceProvider class.
  • Most of them contain a register and a boot method.
  • All of the service providers for the application are configured in the config/app.php configuration file's providers array.
  • Are responsible for bootstrapping all of the framework's various components, such as the database, queue, validation, and routing components.

Service Provider generation

php artisan make:provider RiakServiceProvider

Writing Service Providers

Php artisan make:provider RiakServiceProvider

Registering Providers

'providers' => [
    // Other Service Providers

    App\Providers\ComposerServiceProvider::class,
],

Deferred Providers

<?php

namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection($app['config']['riak']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [Connection::class];
    }

}

Will improve the performance of your application, since it is not loaded from the filesystem on every request.

Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class.

Laravel Service Providers — Structure map

Clickable & Draggable!

Laravel Service Providers — Related pages: