LaravelService Container

Laravel Service Container

The service container is a powerful tool for managing class dependencies and performing dependency injection.

Binding Basics

// Simple binding
$this->app->bind(PaymentGateway::class, function ($app) {
    return new StripeGateway(config('services.stripe.key'));
});

// Binding interfaces to implementations $this->app->bind( PaymentGatewayInterface::class, StripeGateway::class );

// Singleton binding $this->app->singleton(Cache::class, function ($app) { return new RedisCache($app['config']['cache.redis']); });

Automatic Resolution

Laravel can automatically resolve classes without explicit bindings when dependencies can be determined from type hints:

class UserController extends Controller
{
    public function __construct(
        private UserRepository $users,
        private PaymentGateway $payments
    ) {}

public function show(User $user) { // Laravel automatically injects dependencies } }

Contextual Binding

$this->app->when(PhotoController::class)
    ->needs(Filesystem::class)
    ->give(function () {
        return Storage::disk('photos');
    });

$this->app->when(VideoController::class) ->needs(Filesystem::class) ->give(function () { return Storage::disk('videos'); });

Service Providers

class PaymentServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(PaymentGateway::class, function () {
            return new StripeGateway(
                config('services.stripe.key'),
                config('services.stripe.secret')
            );
        });
    }

public function boot() { // Run after all providers are registered } }