loading...

Laravel Service Providers

patelparixit07 profile image Parixit Patel ・3 min read

In this post, we will discuss Service Providers and how Service Providers used to register classes. There are two important methods of service providers Boot and Register. So will discuss these two methods.

Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services, are bootstrapped via service providers.

In simple terms, Service Provider is used for registering things, including registering service container bindings. So it's a place where you can register service container bindings.

Service providers contains register and boot method. Within the register method, you should only define service container bindings. You have always access to service containers from service provider via $this->app.

To register the service provider, you just need to add an entry to the provider's array in the config/app.php file. These are all of the service provider classes that will be loaded for your application.

Let's understand both methods register and boot by creating a custom service provider.

In Laravel, you can use the command-line utility tool Artisan to create custom providers. Just hit below artisan command to create a provider.

php artisan make:provider ProductServiceProvider

This will create new file ProductServiceProvider.php under app/providers.

The content of this file will be looks like :

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ProductServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here, we have created our first custom service provider Now add an entry in providers array under config/app.php file so that laravel loads this provider along with other providers during bootstrapping process.

So open config/app.php file and append line App\Providers\ProductServiceProvider::class

'providers' => [
        App\Providers\ProductServiceProvider::class,
],

Till now we have created a custom service provider and added an entry on providers array. But still, our service provider doesn't do anything special here. it's just a blank template. So let's try to register class binding inside the register method.

Open ProductServiceProvider.php file and update with below code :

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Library\ProductClass;
use App\Repositories\ProductRepository;

class ProductServiceProvider extends ServiceProvider
{
    public function boot()
    {
    }

    public function register()
    {
        $this->app->bind(ProductRepository::class, ProductClass::class);
    }
}

In the register method, we've added our service container binding. So, whenever the App\Repositories\ProductRepository dependency needs to be resolved, it'll call the closure function, and it returns the instance of App\Library\ProductClass class.

Let's create ProductRepository and ProductClass :

App\Repositories\ProductRepository.php

<?php

namespace App\Repositories;

Interface ProductRepository
{
    public function listAll();
}

App\Library\ProductClass.php

<?php

namespace App\Library;

use App\Repositories\ProductRepository;
use App\Models\Products;

class ProductClass implements ProductRepository
{
    public function listAll()
    {
        return Products::all();
    }
}

So we have ProductClass and ProductRepository class created. Now inject dependency somewhere on a controller.

For that, create Controller and put below code inside it :

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\ProductRepository;

class ProductController extends Controller
{
    protected $prodRepository;

    public function __construct(ProductRepository $prodRepository)
    {
        $this->prodRepository = $prodRepository;
    }

    public function index()
    {
        $products = $this->prodRepository->listAll();
        return view('prodducts.list',['products'=>$products]);
    }
}

When the above code executed it will list products on the webpage. This is a basic concept of the service provider and the beauty of this concept is you can easily swap to other implementation. If you need implementation of SomeOtherClass instead of ProductClass then you just need to update ProductServiceProvider binding with other classes.

That's it, We have created custom service provider ProductServiceProvider and bind the ProductRepository interface inside the register method. Then we create ProductClass which implements the ProductRepository interface. And demonstrate how dependency injected on ProductController.

Boot Method

Boot method, which you can use to extend the core functionality or create custom functionality. In this method, you could access all the services that were registered using the register method of the service provider.

For Example,

You could use this method to add a custom validator,

public function boot()
{
    Validator::extend('custom_validator', function ($attribute, $value, $parameters, $validator) {
        // validation logic goes here...
    });
}

You could use to register a view composer,

public function boot()
{
    View::composer(
        'custom', 'App\Http\ViewComposers\CustomComposer'
    );
}

You could use to share the data across multiple views,

public function boot()
{
    View::share('key', 'value');
}

Hope this post helps you to understand Service Provider uses and the creation of custom service providers.

Thank you.

Posted on by:

patelparixit07 profile

Parixit Patel

@patelparixit07

Software Developer looking to develop my skills further particularly around programming & technologies

Discussion

pic
Editor guide