1. How does the Laravel Service Container manage Dependency Injection and Bindings?
❓ Context: Explain IoC (Inversion of Control), Service Providers, Contextual Bindings, and Singleton vs Transient bindings in Laravel 11+.
The Laravel Service Container is a powerful tool for managing class dependencies and performing dependency injection.
Bindings:
Service Providers ('AppServiceProvider') register container bindings before application boot execution.
<?php
namespace AppProviders;
use IlluminateSupportServiceProvider;
use AppServicesPaymentGateway;
use AppServicesStripePaymentGateway;
use AppServicesMockPaymentGateway;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(PaymentGateway::class, function ($app) {
if ($app->environment('testing')) {
return new MockPaymentGateway();
}
return new StripePaymentGateway(config('services.stripe.secret'));
});
}
}Dependency Injection through the Laravel Service Container promotes loose coupling, high testability, and clean architecture.