Symfony Components
Complete reference for all 38 Symfony components — patterns, APIs, configuration, and best practices for PHP 8.3+ and Symfony 7.x.
Component Index
HTTP & Runtime
- HttpFoundation — Object-oriented HTTP requests/responses replacing PHP globals → reference
- HttpKernel — Request handling, kernel events, controller resolution, middleware → reference
- PSR-7 Bridge — Bidirectional HttpFoundation ↔ PSR-7 conversion → reference
- Runtime — Decoupled bootstrapping for multiple runtime environments → reference
Messaging
- Messenger — Sync/async message buses, transports (AMQP, Redis, Doctrine), middleware, envelopes → reference
Console
- Console — CLI commands, input/output handling, helpers, formatters, progress bars → reference
Dependency Injection
- DependencyInjection — Service container, autowiring, compiler passes, tagged services → reference
- Contracts — Decoupled abstractions for interoperability (Cache, EventDispatcher, HttpClient, etc.) → reference
Forms & Validation
- Form — Form creation, field types, events, data transformers, collections, theming → reference
- Validator — JSR-303 constraints, custom validators, groups, severity levels → reference
- OptionsResolver — Option configuration with defaults, validation, normalization, nesting → reference
Cache, Lock & Semaphore
- Cache — PSR-6/PSR-16 adapters, tag-based invalidation, stampede prevention → reference
- Lock — Exclusive resource locking across processes/servers (Redis, PostgreSQL, file) → reference
- Semaphore — Concurrent access with configurable limits (Redis, DynamoDB) → reference
Events & Workflow
- EventDispatcher — Observer/Mediator patterns, listeners, subscribers, priorities → reference
- Workflow — State machines, workflow transitions, guards, metadata, events → reference
Configuration & Expressions
- Config — Configuration loading, validation, caching, tree building, bundle config → reference
- ExpressionLanguage — Safe expression sandbox for business rules, validation, security → reference
- Yaml — YAML parsing, dumping, linting with full data type support → reference
Filesystem, Finder & Process
- Filesystem — Platform-independent file/directory operations, atomic writes, path utils → reference
- Finder — File search with fluent criteria (name, size, date, depth, content) → reference
- Process — Secure system command execution, async processes, output streaming → reference
Serialization & Types
- PropertyAccess — Read/write objects and arrays via string paths (
foo.bar[baz]) → reference
- PropertyInfo — Property metadata extraction (types, access, descriptions) → reference
- TypeInfo — PHP type extraction, resolution, and validation → reference
- VarDumper — Enhanced variable debugging with HTML/CLI formatters → reference
- VarExporter — Export PHP data to OPcache-optimized code, lazy ghost/proxy objects → reference
Testing
- BrowserKit — Simulated browser for programmatic HTTP, cookies, history → reference
- DomCrawler — HTML/XML traversal, CSS selectors, form automation → reference
- CssSelector — CSS-to-XPath conversion for DOM querying → reference
- PHPUnit Bridge — Deprecation reporting, time/DNS mocking, parallel tests → reference
Data & Text Utilities
- Uid — UUID (v1–v8) and ULID generation, conversion, Doctrine integration → reference
- Clock — Testable time abstraction with MockClock and DatePoint → reference
- Intl — Internationalization data (languages, countries, currencies, timezones) → reference
- JsonPath — RFC 9535 JSONPath queries on JSON structures → reference
- Mime — MIME message creation for emails and content types → reference
- Ldap — LDAP/Active Directory connections, queries, and management → reference
- Asset — URL generation and versioning for web assets → reference
Quick Patterns
Dependency Injection (Autowiring)
# services.yaml — most services are autowired automatically
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/'
exclude: '../src/{DI,Entity,Kernel.php}'
Define a Route + Controller
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ArticleController
{
#[Route('/articles/{id}', methods: ['GET'])]
public function show(int $id): Response
{
return new Response("Article $id");
}
}
Dispatch a Message (Async)
use Symfony\Component\Messenger\MessageBusInterface;
class OrderService
{
public function __construct(private MessageBusInterface $bus) {}
public function place(Order $order): void
{
$this->bus->dispatch(new OrderPlaced($order->getId()));
}
}
Create and Validate a Form
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($form->getData());
$em->flush();
return $this->redirectToRoute('article_list');
}
Cache with Tags
use Symfony\Contracts\Cache\ItemInterface;
$value = $cache->get('products_list', function (ItemInterface $item) {
$item->expiresAfter(3600);
$item->tag(['products']);
return $this->repository->findAll();
});
$cache->invalidateTags(['products']);
Console Command
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:process', description: 'Process items')]
class ProcessCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('Processing...');
return Command::SUCCESS;
}
}
Event Subscriber
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [OrderPlacedEvent::class => 'onOrderPlaced'];
}
public function onOrderPlaced(OrderPlacedEvent $event): void
{
// Handle event
}
}
Workflow Transition
if ($workflow->can($article, 'publish')) {
$workflow->apply($article, 'publish');
}
Lock a Resource
$lock = $factory->createLock('pdf-generation', ttl: 30);
if ($lock->acquire()) {
try {
generatePdf();
} finally {
$lock->release();
}
}
Best Practices
- Target PHP 8.3+ and Symfony 7.x with strict typing
- Use attributes over YAML/XML for routes, commands, message handlers, event listeners
- Prefer autowiring — only register services manually when configuration is needed
- Use Cache Contracts (
$cache->get()) over raw PSR-6 for stampede prevention
- Apply validation groups to support multiple form contexts
- Use state machines by default; use workflows only when parallel states are needed
- Create custom constraints for business logic that can't be expressed with built-in ones
- Mock time and DNS in tests using PHPUnit Bridge for deterministic results
1---2name: symfony-components3description: Comprehensive reference for all 38 Symfony framework components with PHP 8.3+ and Symfony 7.x patterns. Use when the user asks to implement, configure, or troubleshoot any Symfony component including HttpFoundation, HttpKernel, DependencyInjection, Form, Validator, Cache, Messenger, Console, EventDispatcher, Workflow, Serializer, Security, Routing, Twig, Doctrine integration, or any other Symfony component. Covers APIs, configuration, best practices, and common pitfalls.4---5
6# Symfony Components
7
8Complete reference for all 38 Symfony components — patterns, APIs, configuration, and best practices for PHP 8.3+ and Symfony 7.x.
9
10## Component Index
11
12### HTTP & Runtime
13- **HttpFoundation** — Object-oriented HTTP requests/responses replacing PHP globals → [reference](references/http-foundation.md)
14- **HttpKernel** — Request handling, kernel events, controller resolution, middleware → [reference](references/http-kernel.md)
15- **PSR-7 Bridge** — Bidirectional HttpFoundation ↔ PSR-7 conversion → [reference](references/psr7-bridge.md)
16- **Runtime** — Decoupled bootstrapping for multiple runtime environments → [reference](references/runtime.md)
17
18### Messaging
19- **Messenger** — Sync/async message buses, transports (AMQP, Redis, Doctrine), middleware, envelopes → [reference](references/messenger.md)
20
21### Console
22- **Console** — CLI commands, input/output handling, helpers, formatters, progress bars → [reference](references/console.md)
23
24### Dependency Injection
25- **DependencyInjection** — Service container, autowiring, compiler passes, tagged services → [reference](references/dependency-injection.md)
26- **Contracts** — Decoupled abstractions for interoperability (Cache, EventDispatcher, HttpClient, etc.) → [reference](references/contracts.md)
27
28### Forms & Validation
29- **Form** — Form creation, field types, events, data transformers, collections, theming → [reference](references/form.md)
30- **Validator** — JSR-303 constraints, custom validators, groups, severity levels → [reference](references/validator.md)
31- **OptionsResolver** — Option configuration with defaults, validation, normalization, nesting → [reference](references/options-resolver.md)
32
33### Cache, Lock & Semaphore
34- **Cache** — PSR-6/PSR-16 adapters, tag-based invalidation, stampede prevention → [reference](references/cache.md)
35- **Lock** — Exclusive resource locking across processes/servers (Redis, PostgreSQL, file) → [reference](references/lock.md)
36- **Semaphore** — Concurrent access with configurable limits (Redis, DynamoDB) → [reference](references/semaphore.md)
37
38### Events & Workflow
39- **EventDispatcher** — Observer/Mediator patterns, listeners, subscribers, priorities → [reference](references/event-dispatcher.md)
40- **Workflow** — State machines, workflow transitions, guards, metadata, events → [reference](references/workflow.md)
41
42### Configuration & Expressions
43- **Config** — Configuration loading, validation, caching, tree building, bundle config → [reference](references/config.md)
44- **ExpressionLanguage** — Safe expression sandbox for business rules, validation, security → [reference](references/expression-language.md)
45- **Yaml** — YAML parsing, dumping, linting with full data type support → [reference](references/yaml.md)
46
47### Filesystem, Finder & Process
48- **Filesystem** — Platform-independent file/directory operations, atomic writes, path utils → [reference](references/filesystem.md)
49- **Finder** — File search with fluent criteria (name, size, date, depth, content) → [reference](references/finder.md)
50- **Process** — Secure system command execution, async processes, output streaming → [reference](references/process.md)
51
52### Serialization & Types
53- **PropertyAccess** — Read/write objects and arrays via string paths (`foo.bar[baz]`) → [reference](references/property-access.md)
54- **PropertyInfo** — Property metadata extraction (types, access, descriptions) → [reference](references/property-info.md)
55- **TypeInfo** — PHP type extraction, resolution, and validation → [reference](references/type-info.md)
56- **VarDumper** — Enhanced variable debugging with HTML/CLI formatters → [reference](references/var-dumper.md)
57- **VarExporter** — Export PHP data to OPcache-optimized code, lazy ghost/proxy objects → [reference](references/var-exporter.md)
58
59### Testing
60- **BrowserKit** — Simulated browser for programmatic HTTP, cookies, history → [reference](references/browser-kit.md)
61- **DomCrawler** — HTML/XML traversal, CSS selectors, form automation → [reference](references/dom-crawler.md)
62- **CssSelector** — CSS-to-XPath conversion for DOM querying → [reference](references/css-selector.md)
63- **PHPUnit Bridge** — Deprecation reporting, time/DNS mocking, parallel tests → [reference](references/phpunit-bridge.md)
64
65### Data & Text Utilities
66- **Uid** — UUID (v1–v8) and ULID generation, conversion, Doctrine integration → [reference](references/uid.md)
67- **Clock** — Testable time abstraction with MockClock and DatePoint → [reference](references/clock.md)
68- **Intl** — Internationalization data (languages, countries, currencies, timezones) → [reference](references/intl.md)
69- **JsonPath** — RFC 9535 JSONPath queries on JSON structures → [reference](references/json-path.md)
70- **Mime** — MIME message creation for emails and content types → [reference](references/mime.md)
71- **Ldap** — LDAP/Active Directory connections, queries, and management → [reference](references/ldap.md)
72- **Asset** — URL generation and versioning for web assets → [reference](references/asset.md)
73
74## Quick Patterns
75
76### Dependency Injection (Autowiring)
77
78```yaml
79# services.yaml — most services are autowired automatically
80services:
81 _defaults:
82 autowire: true
83 autoconfigure: true
84 App\:
85 resource: '../src/'
86 exclude: '../src/{DI,Entity,Kernel.php}'
87```
88
89### Define a Route + Controller
90
91```php
92use Symfony\Component\HttpFoundation\Response;
93use Symfony\Component\Routing\Attribute\Route;
94
95class ArticleController
96{
97 #[Route('/articles/{id}', methods: ['GET'])]
98 public function show(int $id): Response
99 {
100 return new Response("Article $id");
101 }
102}
103```
104
105### Dispatch a Message (Async)
106
107```php
108use Symfony\Component\Messenger\MessageBusInterface;
109
110class OrderService
111{
112 public function __construct(private MessageBusInterface $bus) {}
113
114 public function place(Order $order): void
115 {
116 $this->bus->dispatch(new OrderPlaced($order->getId()));
117 }
118}
119```
120
121### Create and Validate a Form
122
123```php
124$form = $this->createForm(ArticleType::class, $article);
125$form->handleRequest($request);
126
127if ($form->isSubmitted() && $form->isValid()) {
128 $em->persist($form->getData());
129 $em->flush();
130 return $this->redirectToRoute('article_list');
131}
132```
133
134### Cache with Tags
135
136```php
137use Symfony\Contracts\Cache\ItemInterface;
138
139$value = $cache->get('products_list', function (ItemInterface $item) {
140 $item->expiresAfter(3600);
141 $item->tag(['products']);
142 return $this->repository->findAll();
143});
144
145$cache->invalidateTags(['products']);
146```
147
148### Console Command
149
150```php
151use Symfony\Component\Console\Attribute\AsCommand;
152use Symfony\Component\Console\Command\Command;
153use Symfony\Component\Console\Input\InputInterface;
154use Symfony\Component\Console\Output\OutputInterface;
155
156#[AsCommand(name: 'app:process', description: 'Process items')]
157class ProcessCommand extends Command
158{
159 protected function execute(InputInterface $input, OutputInterface $output): int
160 {
161 $output->writeln('Processing...');
162 return Command::SUCCESS;
163 }
164}
165```
166
167### Event Subscriber
168
169```php
170use Symfony\Component\EventDispatcher\EventSubscriberInterface;
171
172class OrderSubscriber implements EventSubscriberInterface
173{
174 public static function getSubscribedEvents(): array
175 {
176 return [OrderPlacedEvent::class => 'onOrderPlaced'];
177 }
178
179 public function onOrderPlaced(OrderPlacedEvent $event): void
180 {
181 // Handle event
182 }
183}
184```
185
186### Workflow Transition
187
188```php
189if ($workflow->can($article, 'publish')) {
190 $workflow->apply($article, 'publish');
191}
192```
193
194### Lock a Resource
195
196```php
197$lock = $factory->createLock('pdf-generation', ttl: 30);
198if ($lock->acquire()) {
199 try {
200 generatePdf();
201 } finally {
202 $lock->release();
203 }
204}
205```
206
207## Best Practices
208
209- Target **PHP 8.3+** and **Symfony 7.x** with strict typing
210- Use **attributes** over YAML/XML for routes, commands, message handlers, event listeners
211- Prefer **autowiring** — only register services manually when configuration is needed
212- Use **Cache Contracts** (`$cache->get()`) over raw PSR-6 for stampede prevention
213- Apply **validation groups** to support multiple form contexts
214- Use **state machines** by default; use workflows only when parallel states are needed
215- Create **custom constraints** for business logic that can't be expressed with built-in ones
216- Mock **time and DNS** in tests using PHPUnit Bridge for deterministic results