SyntaxStudy
Sign Up
Laravel Service Container and Service Providers
Laravel Beginner 1 min read

Service Container and Service Providers

The Laravel service container is an inversion-of-control container responsible for managing class dependencies and performing dependency injection. When you type-hint a class or interface in a constructor or method, Laravel automatically resolves and injects the correct implementation. This makes code loosely coupled, easily testable, and straightforward to swap implementations without touching calling code. Service providers are the bootstrap layer of a Laravel application. Every provider has a register() method for binding things into the container and an optional boot() method for performing actions after all providers are registered. Laravel's own framework packages are bootstrapped through core providers listed in config/app.php, and you can add your own providers to the same array. Bindings can be singletons, meaning the same object instance is returned every time, or transient, where a fresh instance is created on each resolution. Facades provide a static-style interface to underlying container bindings, making them convenient to call from anywhere while still remaining testable through the container's fake/swap mechanisms.
Example
<?php
// app/Providers/AppServiceProvider.php

namespace App\Providers;

use App\Contracts\PaymentGateway;
use App\Services\StripePaymentGateway;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Bind the interface to a concrete implementation
        $this->app->bind(PaymentGateway::class, function ($app) {
            return new StripePaymentGateway(
                config('services.stripe.secret')
            );
        });

        // Register a singleton (resolved only once)
        $this->app->singleton('analytics', function ($app) {
            return new \App\Services\AnalyticsService(
                config('services.analytics.key')
            );
        });
    }

    public function boot(): void
    {
        // Actions run after all providers are registered
        \Illuminate\Pagination\Paginator::useBootstrapFive();
    }
}