Services and DI
| A plain service | |
| Autowiring | |
| Bind in services.yaml | |
| Lazy note |
A plain service
A service is a plain PHP class that does one job well: slugs, mailers, price math. No base class is required, which keeps the code easy to test.
Keep services small and stateless when possible. Input goes in through method arguments, and output comes back as a return value.
class Slugger { public function slug(string $title): string { return strtolower(trim($title)); } }
Autowiring
Autowiring connects services through constructor type hints. Ask for a Slugger in the constructor and the container builds and passes it.
No configuration is needed for the common case. The container reads the type, finds the matching service, and injects it on every request.
public function __construct(private Slugger $slugger) { } $slug = $this->slugger->slug("Hello Symfony");
Bind in services.yaml
Scalar values like emails and limits cannot autowire, because many strings look alike. The bind section maps an argument name to one value for the whole application.
Any constructor argument named adminEmail below receives that address. Rename the argument and the binding stops matching, which fails fast and loud.
services: _defaults: bind: $adminEmail: "admin@example.com"
Lazy note
Heavy services should not slow every request. Lazy services build a light proxy at boot and create the real object on first real use.
Mark the service lazy in the same services file. Most projects need this for only one or two expensive builders.
services: App/Service/ReportBuilder: lazy: true
Next: JSON controllers
Article author: Arthur Isaev