Beginner LevelLaravel
How does the Laravel Service Container manage Dependency Injection and Bindings?
❓ Interview Prompt: 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:
•
'bind()': Creates a new instance every time the class is resolved from the container.
•
'singleton()': Resolves the class once and returns the exact same cached instance on subsequent calls.
•
'scoped()': Acts as a singleton within a single HTTP request execution lifecycle, but resets for subsequent requests.
Service Providers ('AppServiceProvider') register container bindings before application boot execution.
Code Implementation Example
php
<?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'));
});
}
}💡Laravel Service Provider registering interface singleton binding.
🎯 Interview Key Takeaway
Dependency Injection through the Laravel Service Container promotes loose coupling, high testability, and clean architecture.
#Laravel#PHP#Service Container#Dependency Injection#Beginner
Back to all Laravel Questions→