Services and DI

Contents
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

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: