Skip to content

Glossary

Dependency injection in Laravel: what you need is handed to you

A principle in which a part of the program is given what it needs instead of fetching it itself.

A part of a program almost always needs other parts. A connection to the database, a service for sending email, access to another system. The question is how it gets hold of them. Either it fetches them itself, or they are handed over when it is created. The second is dependency injection.

The difference sounds academic and has very practical consequences. Fetch your own dependencies and you fix what they are. Have them handed to you and you accept anything of the right shape.

What that actually buys

Two things. First, replaceability: a different provider for shipping or payment is entered in one place rather than hunted down in thirty places in the code.

Second, testability. In an automated test you want to send no real email and call no real outside system. If the dependencies are handed over, the test simply puts a stand-in in place. If they are fetched, often the only option left is to leave the test out.

Putting all this together in Laravel is the job of the service container, which knows how each service is created.

FAQ

Häufige Fragen

Sounds like more effort for the same result.
At first glance, yes. The difference shows as soon as something has to be swapped: a different shipping provider, a different payment method, or a stand-in during a test that sends no real email. Fetch your dependencies yourself and you have to change the code for that. Have them handed to you and you do not.

Related

Terms that belong with this one

A project, or a question?

Write and tell us what it is about. You get an assessment from somebody who works with Laravel themselves, not from a sales desk.