architecture
Junior
Explain the service container
Short Answer
The service container (IoC) is Laravel's dependency injection container that manages class dependencies and performs automatic injection.
Detailed Answer
The service container is the heart of Laravel\'s architecture:
1. Bind: Register how a class should be resolved
$app->bind(Service::class, ConcreteService::class)
2. Singleton: Register so only one instance is created
$app->singleton(Cache::class, RedisCache::class)
3. Resolve: Get an instance from the container
$service = app(Service::class)
4. Auto-resolution: If not bound, the container resolves automatically using reflection
How it works:
- Constructor injection: Automatically resolves type-hinted dependencies
- Method injection: Resolves parameters in controller methods
- Interface binding: Bind interfaces to concrete implementations
The container makes dependency injection natural in Laravel.
Code Example
Example
<?php
// Binding
$this->app->bind(PostRepositoryInterface::class, function ($app) {
return new EloquentPostRepository(new Post);
});
$this->app->singleton(Mailer::class, function ($app) {
return $app->make('mailer');
});
// Constructor injection - container auto-resolves
public function __construct(
private PostRepositoryInterface $repository,
private Mailer $mailer
) {}
// Method injection in controllers
public function store(Request $request, PostService $service)
{
$post = $service->create($request->validated());
}
// Manual resolution
$service = app(PostService::class);
$service = app()->make(PostService::class);
Interview Tip
Explain that auto-resolution works without explicit binding when all constructor dependencies can be resolved. Binding is needed for interfaces or when you want custom behavior.