Interview question
What is the service container in Laravel? Laravel में service container क्या है?
Answer
The service container is a tool for managing class dependencies and performing dependency injection - it automatically resolves and injects classes your code depends on.
// Binding in a service provider
$this->app->bind(PaymentGateway::class, function ($app) {
return new StripeGateway(config('services.stripe.key'));
});
// Automatic resolution via type-hinting
class OrderController extends Controller
{
public function __construct(protected PaymentGateway $gateway) {}
}Because Laravel resolves PaymentGateway automatically, you can swap StripeGateway for a different implementation (e.g. in tests) without changing the controller.
Service container एक tool है जो class dependencies को manage करता है और dependency injection करता है - आपकी classes के dependencies को automatically resolve करता है।
$this->app->bind(PaymentGateway::class, function ($app) {
return new StripeGateway(config('services.stripe.key'));
});
class OrderController extends Controller
{
public function __construct(protected PaymentGateway $gateway) {}
}Was this answer clear?