Difficulty: Intermediate → Advanced
Dependency injection means providing a class with the objects it needs instead of having the class construct those objects itself.
Consider:
class OrderController { public function __construct( private OrderService $orderService ) {} }
Laravel's service container can resolve the dependency.
The controller doesn't need:
$this->orderService = new OrderService();
This provides several benefits:
Loose coupling Testability Maintainability Replaceable implementations Cleaner architecture
For example, you could depend on an interface:
interface PaymentGateway { public function charge(int $amount): bool; }
and inject an implementation.
This becomes especially useful when an application supports:
Stripe PayPal Razorpay Internal payment gateway Mock payment gateway for testing
0 comments:
Post a Comment
Thanks