Menu

1 / 6

app() Is Not Dependency Injection: 18 Calls Down to Zero

DEV Community: php·Ivan Mykhavko·3 days ago
#geSuQwPy
#devto#dev#class#service#laravel
Reading 0:00
15s threshold

I keep hearing "we use DI everywhere" from Laravel devs whose code is full of app(SomeService::class) . The container builds the object, so it feels like DI. It's not. It's Service Locator, and I've said so in code reviews for years.

And still, when I went through the git history of the project I work on, I counted 18 of these calls at the peak. Knowing it's an anti-pattern and not writing it are two different things. This is how that gap closed.

"But We Use DI Everywhere"

Here's what I mean. Both of these get their dependency from the container. The first one is from our codebase in 2024:

// app/Models/User.php, 2024: Service Locator, the class asks for it public function getCart (): Cart { /** @var CartService $cartService */ $cartService = app ( CartService :: class );

return $cartService -> getCartEntity ( $this ); }

Enter fullscreen mode

Exit fullscreen mode

The second one is how a cart action looks on our main branch today:

// app/Actions/Cart/CartIndexAction.php, today: dependency injection,…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.