$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[May 13, 2024] Laravel

Laravel IoC Container: Dependency Injection

Laravel IoC Container: Dependency Injection

────────────────────────────────────────────────────────

Laravel IoC Container: Dependency Injection

Tip: Automatic Injection

public function __construct(protected UserService $users) {}

Laravel resolves UserService automatically. No manual binding needed for concrete classes.

Gotcha: Interface Binding Required

$this->app->bind(PaymentInterface::class, StripePayment::class);

Interfaces can't be auto-resolved. You must tell Laravel which implementation to use.

Tip: Contextual Binding

$this->app->when(OrderController::class)
    ->needs(PaymentInterface::class)
    ->give(PayPalPayment::class);

Different implementations for different consumers.

Gotcha: Circular Dependencies

If A needs B and B needs A, resolution fails. Break the cycle with events or a mediator.

Tip: app() Helper

$service = app(ServiceInterface::class);

Quick resolution outside constructors.

Gotcha: Singleton vs Bind

singleton() returns the same instance every time. bind() creates a new instance on each resolution.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

The service container is one of those features that seems simple until it isn't. I once spent six hours debugging why a singleton wasn't behaving like one — turned out a service provider was registering it in register() but then rebinding it in boot(), creating two instances. The lesson: use $app->tagged() and $app->make() deliberately, and always verify your bindings with php artisan tinker before assuming they work as expected.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts