Hi guys,
In this article, We are studying Service Providers. It is the central place of all laravel application bootstrapping. You can be bootstrapping custom classes and laravel core classes, which contain registering service container bindings, event listeners, middleware, and custom routes.
You can see providers inside the config/app.php file. It contains the Providers array. You can specify your service providers and already contain a set of laravel core service providers and Provider loads on a specific route. You will learn how to write and register your service provider in the laravel application.
Create a Service Provider
All Service Provider extends the Illuminate\Support\ServiceProvider class. Run the below command to make your service provider.
php artisan make:provider InstallServiceProvider
It contains a register and boot method. In the register method, you can specify only bind things into the service container. You should not register any event listeners or routes.
Register method:
You should not register any event listeners, routes, or functionality within the register method of a service container. Instead, only bind things in the container. You can access the $app property, which provides access to the service container.
<?php
namespace App\Providers;
use App\Services\Riak\Connection;
use Illuminate\Support\ServiceProvider;
class RiakServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton(Connection::class, function ($app) {
return new Connection(config('riak'));
});
}
}
Bindings and Singletons Properties:
You want to register many service providers in a simple binding using bindings and singletons properties. It will automatically check these properties and register their bindings.
<?php
namespace App\Providers;
use App\Contracts\DowntimeNotifier;
use App\Contracts\ServerProvider;
use App\Services\DigitalOceanServerProvider;
use App\Services\PingdomDowntimeNotifier;
use App\Services\ServerToolsProvider;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* All of the container bindings that should registered.
*
* @var array
*/
public $bindings = [
ServerProvider::class => DigitalOceanServerProvider::class,
];
/**
* All of the container singletons that should be registered.
*
* @var array
*/
public $singletons = [
DowntimeNotifier::class => PingdomDowntimeNotifier::class,
ServerProvider::class => ServerToolsProvider::class,
];
}
Top comments (0)