Friday, 6 September 2024

Service, service Container, service Providers in laravel

1. Service is a class to perform some feature, or logic in the Laravel app
2. Service Container is a place containing registered services in the Larravel app
3. The Service Provider serves as a bridge to register services to the service container
- To register a service for Service Container you can register it in the service provider, you can use the bind() or singleton() method
$this->app->bind('App\Services\PaymentGateway', function ($app) {
    return new \App\Services\PaymentGateway(config('services.payment.api_key'));
});

$this->app->singleton('App\Services\PaymentGateway', function ($app) {
    return new \App\Services\PaymentGateway(config('services.payment.api_key'));
});

- To register a service provider to Laravel, there are 2 ways:
(1) Config Service provider in config/app.php
'providers' => [
    // Other Service Providers

    App\Providers\MyCustomServiceProvider::class,
],

(2) Config service provider in composer.json

"extra": {
    "laravel": {
        "providers": [
            "Vendor\\Package\\ServiceProvider"
        ],
        "aliases": {
            "SomeAlias": "Vendor\\Package\\Facade"
        }
    }
}

Thank you

No comments:

Post a Comment

Golang Advanced Interview Q&A