Skip to content

Service Location Is a Hidden Dependency

Quick Tips•
October 29, 2026

When a handler reaches into the container mid-method with app() or resolve(), its real dependencies disappear from the constructor. You cannot tell what the class needs without reading every line, and the next person to add app(Mailer::class) three lines down adds a dependency no signature admits. A test cannot swap the gateway without booting the Laravel application.

Don't do this:

PHP
<?php declare(strict_types=1); namespace App\Billing; final readonly class ChargeCustomerHandler { public function handle(ChargeCustomer $command): void { $gateway = app(PaymentGateway::class); $gateway->charge($command->customerId, $command->amount); } }

Do this instead:

PHP
<?php declare(strict_types=1); namespace App\Billing; final readonly class ChargeCustomerHandler { public function __construct( private PaymentGateway $gateway, ) {} public function handle(ChargeCustomer $command): void { $this->gateway->charge($command->customerId, $command->amount); } }

The constructor lists every collaborator the handler uses, so the signature documents the class. A test calls new ChargeCustomerHandler($fakeGateway) and never touches the container. The container still builds the handler and injects the gateway, and a missing binding now fails when the handler is resolved instead of halfway through handle().