DI

What is it?

Dependency Injection (DI) is a design pattern where an object receives its dependencies from the outside instead of creating them itself. It is a form of Inversion of Control: the responsibility for creating and configuring services is handled by a container or provider (for example Laravel's service container), not by the consumer. In PHP backend/web development DI reduces coupling, improves testability, and makes it simple to swap or configure implementations (for example different repositories or gateways).

Practical example

Imagine you have a PaymentGateway interface in a Laravel app and multiple implementations (Stripe, PayPal). In a ServiceProvider you bind the interface to a concrete class, e.g. $this->app->bind(PaymentGateway::class, StripePayment::class). Then inject the interface into a controller via the constructor: public function __construct(PaymentGateway $gateway) { $this->gateway = $gateway; }. For testing you can override that binding with a mock or fake so the controller can be tested without performing real payments. This avoids using new inside the controller and keeps the code modular and easily replaceable.

Test your knowledge

Which statement about Dependency Injection in Laravel is correct?

Ask Lex
Lex knows the context of this term and can give targeted explanations, examples, and extra context.
Tip: Lex replies briefly in the widget. For more detail, go to full screen mode.

Learn our language

Learn these terms from real professionals and take your skills further at KdG MCT.

Study at KdG