❌ Without Service Container (Hard-coded)
Manual object creation - tight coupling, hard to test
$payment = new StripePaymentService();
$notification = new NotificationService();
$order = new OrderService($payment, $notification);
// If you want to switch to PayPal, you must edit this code!
Problems:
- • Hard-coded dependencies
- • Difficult to test (can't mock services)
- • Must manually manage all dependencies
- • Changing payment provider requires code changes
✅ With Service Container (Auto-injected)
Laravel automatically injects dependencies - flexible, testable
public function containerBasics(OrderService $orderService) {
// Laravel automatically resolved:
// 1. OrderService needs PaymentServiceInterface
// 2. Container provides bound implementation (Stripe/PayPal)
// 3. OrderService needs NotificationService
// 4. Container creates NotificationService
// All done automatically!
}
Benefits:
- • Zero manual object creation
- • Easy to swap implementations via bindings
- • Fully testable with mocks
- • Change payment provider via config, not code
🚀 Live Example - Order Processed with DI
Order Details
- Order ID:
- ORD-2116
- Payment Provider:
- Stripe Payment Gateway
- Amount Charged:
- $99.99
Payment Result
- Status:
- ✓ Success
- Transaction ID:
- stripe_693d4e2c79b06
- Processing Fee:
- $3.20
- Notifications Sent:
- 1
🎯 What just happened: Laravel automatically injected OrderService
into the controller, which had PaymentServiceInterface and
NotificationService injected into IT.
The container resolved the entire dependency tree automatically! Currently using Stripe Payment Gateway
(change it in AppServiceProvider to switch providers without touching this code).
💡 Try It Yourself
Step 1: Open app/Providers/AppServiceProvider.php
Step 2: Change line 17 from StripePaymentService::class to PayPalPaymentService::class
Step 3: Refresh this page and see the payment provider change without touching any controller code!