"Laravel'in sihirli gücü nereden geliyor?" diye hiç merak ettiniz mi? İşte bu gücün kaynağı: Dependency Injection (DI) ve Service Container sistemi! Gelin bu güçlü mekanizmayı birlikte keşfedelim.
Dependency Injection (Bağımlılık Enjeksiyonu), bir sınıfın ihtiyaç duyduğu bağımlılıkların dışarıdan verilmesi prensibidir. Laravel'de 3 temel DI yöntemi vardır:
class PaymentController { protected $paymentService; public function __construct(PaymentService $paymentService) { $this->paymentService = $paymentService; } }
public function process(PaymentService $paymentService) { $paymentService->charge(); }
public function setPaymentService(PaymentService $paymentService) { $this->paymentService = $paymentService; }
Laravel'in Service Container'ı, bağımlılıkları yöneten ve otomatik olarak çözümleyen güçlü bir sistemdir.
// AppServiceProvider içinde $this->app->bind('PaymentService', function($app) { return new PaymentService(config('payment.api_key')); });
$this->app->singleton('Analytics', function() { return new AnalyticsService(); });
$this->app->bind( PaymentGatewayInterface::class, StripePaymentGateway::class );
$payment = app('PaymentService');
$payment = $this->app->make('PaymentService');
$payment = resolve('PaymentService');
Belirli durumlarda farklı implementasyonlar sağlamak için:
$this->app->when(EmailController::class) ->needs(MailerInterface::class) ->give(SesMailer::class);
Laravel, type-hint edilen sınıfları otomatik olarak çözümler:
// Laravel otomatik olarak UserRepository örneği oluşturur public function __construct(UserRepository $users) { $this->users = $users; }
$this->app->bind( UserRepositoryInterface::class, EloquentUserRepository::class ); // Controller'da public function __construct(UserRepositoryInterface $users) { $this->users = $users; }
$this->app->singleton('Geocoder', function() { return new GoogleMapsGeocoder(config('services.google.maps_key')); });
Container'ın çalışmasını izlemek için:
$this->app->resolving(function($object, $app) { // Nesne çözümlendiğinde çalışır }); $this->app->afterResolving(function($object, $app) { // Çözümleme tamamlandığında çalışır });
Laravel'in DI ve Service Container sistemi sayesinde:
Bu patternleri projelerinizde nasıl kullanıyorsunuz? Yorumlarda deneyimlerinizi paylaşın! 💬
Bir sonraki yazımız: 🚀 [Laravel'de API Resource: Veri Dönüşümü ve Formatlama] - API yanıtlarınızı profesyonelce yönetin!
#Laravel #DependencyInjection #ServiceContainer #DesignPatterns #PHP 🚀