PHP › Dependency Injection & Service Containers
How does the dependency inversion principle relate to dependency injection, and how does designing around abstractions rather than concrete classes improve long term maintainability?
AdvancedAnswer
The dependency inversion principle states that high level modules should not depend directly on low level modules, but both should depend on abstractions, meaning a class handling important business logic should depend on an interface rather than a specific concrete implementation, and combining this principle with dependency injection lets an application's core logic remain stable and unaffected even as the underlying concrete implementations, such as which specific payment gateway or email provider is used, change over time.
interface PaymentGateway {
public function charge(float $amount): bool;
}
class CheckoutService {
public function __construct(private PaymentGateway $gateway) {}
}Real-world example A company switches payment processors entirely, from one provider to a completely different one, without modifying a single line of their core checkout business logic, since that logic was always designed to depend only on a PaymentGateway interface rather than any specific provider's concrete class.