Service Container adalah fitur inti Laravel yang mengelola dependency injection secara otomatis.
Tanpa DI (hardcoded dependency):
class OrderController {
public function store() {
$payment = new StripePayment(); // Hardcoded!
$payment->charge(100000);
}
}
Dengan DI (injected):
class OrderController {
public function store(PaymentGateway $payment) {
$payment->charge(100000);
// Laravel otomatis inject implementasi yang benar!
}
}
Binding di Service Provider:
// AppServiceProvider.php
public function register(): void
{
$this->app->bind(PaymentGateway::class, StripePayment::class);
}
Sekarang bisa swap implementasi:
// Development
$this->app->bind(PaymentGateway::class, FakePayment::class);
// Production
$this->app->bind(PaymentGateway::class, StripePayment::class);
Keuntungan:
- Kode tidak tergantung pada implementasi spesifik
- Mudah testing (inject mock/fake)
- Swap implementasi tanpa ubah controller