DELAPARRA
Index
Color
NL
Category: Core glossary

Dependency injection

Explained by Updated

What is Dependency injection?

Dependency injection: A design pattern where objects receive their dependencies from an external source rather than creating them internally. Improves testability and decoupling. Dependency injection means a class receives the things it needs from outside, instead of creating them itself. An InvoiceService gets a Mailer passed into its constructor rather than calling new SmtpMailer() inside.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about Dependency injection

How is Dependency injection used in practice?

The main benefit is testing. In a test you pass a fake mailer that records messages instead of sending them. The service does not know or care. It also makes swapping implementations easy, such as moving from one email provider to another.

What should you keep in mind with Dependency injection?

Frameworks like Laravel and Symfony have a service container that does the wiring for you. You type-hint a class or interface in a constructor, and the container provides it. Keep constructors honest: if a class needs eight dependencies, that usually means it is doing too much and should be split up.

At a glance

CategoryCore glossary
Explained by
Updated

More Core glossary terms

All terms starting with D

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.