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.
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.
Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, r
Apply Spatie's Laravel and PHP coding standards for any task that creates, edits, reviews, refactors, or formats Laravel/PHP code or Blade templates; use for controllers, Eloquent models, routes, config, validation, migrations, tests, and related files to align with Laravel conventions and PSR-12.
Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.