TechnicalHard PHP & Laravel
What is the Laravel service container and how does dependency injection work?
Asked for Backend Developer, Full-Stack Developer
Why they ask this: Shows you understand the core of the framework and can write testable, loosely coupled code.
Answer
Dependency injection (DI) means a class receives the objects it needs (its dependencies) from outside, usually through the constructor, instead of creating them itself. This makes code easier to test and swap.
The service container is Laravel's tool for building objects and their dependencies. It uses reflection on type hints to auto-resolve concrete classes, so this works with no configuration:
php
class InvoiceController
{
public function __construct(private InvoiceService $invoices) {}
}For interfaces, you tell the container which implementation to use, usually in a service provider:
php
$this->app->bind(PaymentGateway::class, KhaltiGateway::class);
$this->app->singleton(ExchangeRates::class, fn () => new ExchangeRates(config('services.nrb.url')));Benefits:
- In tests you can replace an implementation with a fake:
$this->app->instance(PaymentGateway::class, new FakeGateway). - Switching from eSewa to Khalti only changes one binding, not every class that uses the gateway.
Can you explain this in your own words?