Lesson 2 of 9 · 25m
Dependency Injection Without Container Voodoo
Autowiring, service ids, constructor injection, environment-specific wiring, and the container mistakes that turn maintenance into archaeology.
The service container is Symfony's superpower and its most abused feature. Used well, dependencies are visible and replaceable. Used badly, it becomes a hidden global variable bag where every object can reach every other object.
Constructor injection is the default
final class RefundService
{
public function __construct(
private PaymentGateway $gateway,
private RefundRepository $refunds,
private LoggerInterface $logger,
) {}
}If the constructor hurts, that is information. Too many dependencies means the service owns too many responsibilities. Hiding that pain with setter injection or service location does not reduce complexity; it hides it.
Let autowiring do boring work
# config/services.yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/'
exclude: ['../src/Entity/', '../src/Kernel.php']autowire resolves type-hints, autoconfigure applies conventional tags, and public: false lets the compiled container inline or remove unused services. Public services are API surface whether you intended that or not.
Bind choices explicitly
services:
App\Billing\PaymentGateway: '@App\Billing\StripeGateway'
App\Billing\InvoiceMailer:
arguments:
$fromAddress: '%env(MAILER_FROM)%'Interfaces do not say which implementation to use; wire the default deliberately. Environment variables configure deployment — hosts, secrets, credentials — not architectural identity.
Service locator syndrome
Injecting the whole container because "sometimes we need things" makes dependencies invisible and circular references easy. If an extension point is genuinely dynamic, inject a narrow tagged locator and name the contract. Compile-time container errors are design feedback: circular references usually mean a missing intermediate service, not a need for lazy proxies everywhere.
Field notes
bin/console debug:container App\\Billing\\PaymentGatewayshows the chosen implementation.bin/console lint:containercatches bad references before production traffic does.- Decorate services for cross-cutting behavior instead of editing vendor classes.
- If every test needs the full container, you probably built service locators, not services.
Was this lesson helpful?