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