Skip to content

Glossary

Laravel service container: how dependencies come together

The mechanism that supplies classes with what they depend on, instead of each one seeing to it itself.

A class rarely needs only itself. Sending an invoice needs a mailer, which in turn needs credentials. The question is who puts these parts together.

The obvious answer would be that each class fetches its own dependencies. That ties it firmly to one particular implementation. The service container turns it round. A class states what it needs and is given it. The principle behind that is called dependency injection.

Why it counts in practice

First, tests. If a class is given its mailer, a stand-in can step in during a test that sends nothing but records what would have been sent. Without that separation, every test would have to produce real mail or be left out altogether.

Second, replaceability. Changing a payment or shipping provider then touches a single place rather than every class using it.

Third, clarity. What a class needs stands visibly in its signature rather than turning up hidden somewhere inside it.

FAQ

Häufige Fragen

Does a client need to know about this?
Not in detail. What matters is the consequence: an application following this pattern can be tested and swapped in parts, when a payment provider changes for instance. One that does not turns that into a project.

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.