symfony-components
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSymfony Components
Symfony 组件
Complete reference for all 38 Symfony components — patterns, APIs, configuration, and best practices for PHP 8.3+ and Symfony 7.x.
完整收录全部38个Symfony组件的参考指南,包含适配PHP 8.3+和Symfony 7.x的开发模式、API、配置方案及最佳实践。
Component Index
组件索引
HTTP & Runtime
HTTP与运行时
- 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
- HttpFoundation —— 面向对象的HTTP请求/响应实现,可替代PHP全局变量 → 参考文档
- HttpKernel —— 请求处理、内核事件、控制器解析、中间件 → 参考文档
- PSR-7 Bridge —— HttpFoundation与PSR-7格式的双向转换工具 → 参考文档
- Runtime —— 适用于多种运行环境的解耦启动引导工具 → 参考文档
Messaging
消息队列
- Messenger — Sync/async message buses, transports (AMQP, Redis, Doctrine), middleware, envelopes → reference
- Messenger —— 同步/异步消息总线、传输器(AMQP、Redis、Doctrine)、中间件、信封 → 参考文档
Console
命令行
- Console — CLI commands, input/output handling, helpers, formatters, progress bars → reference
- Console —— CLI命令开发、输入/输出处理、助手工具、格式化器、进度条 → 参考文档
Dependency Injection
依赖注入
- DependencyInjection — Service container, autowiring, compiler passes, tagged services → reference
- Contracts — Decoupled abstractions for interoperability (Cache, EventDispatcher, HttpClient, etc.) → reference
- DependencyInjection —— 服务容器、自动装配、编译器passes、带标签服务 → 参考文档
- Contracts —— 用于实现互操作性的解耦抽象层(缓存、EventDispatcher、HttpClient等) → 参考文档
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
- Form —— 表单创建、字段类型、事件、数据转换器、集合、主题化 → 参考文档
- Validator —— JSR-303约束、自定义验证器、分组、严重级别设置 → 参考文档
- OptionsResolver —— 支持默认值、验证、规范化、嵌套的选项配置工具 → 参考文档
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
- Cache —— PSR-6/PSR-16适配器、基于标签的失效、防惊群机制 → 参考文档
- Lock —— 跨进程/跨服务器的资源独占锁(支持Redis、PostgreSQL、文件) → 参考文档
- Semaphore —— 支持配置并发数的访问控制工具(支持Redis、DynamoDB) → 参考文档
Events & Workflow
事件与工作流
- EventDispatcher — Observer/Mediator patterns, listeners, subscribers, priorities → reference
- Workflow — State machines, workflow transitions, guards, metadata, events → reference
- EventDispatcher —— 观察者/中介者模式实现、监听器、订阅器、优先级设置 → 参考文档
- Workflow —— 状态机、工作流流转、守卫、元数据、事件 → 参考文档
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
- Config —— 配置加载、验证、缓存、树结构构建、Bundle配置 → 参考文档
- ExpressionLanguage —— 适用于业务规则、验证、安全场景的安全表达式沙箱 → 参考文档
- Yaml —— 支持完整数据类型的YAML解析、导出、语法检查工具 → 参考文档
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
- Filesystem —— 跨平台的文件/目录操作、原子写入、路径工具 → 参考文档
- Finder —— 支持链式条件(名称、大小、日期、深度、内容)的文件搜索工具 → 参考文档
- Process —— 安全的系统命令执行、异步进程、输出流处理 → 参考文档
Serialization & Types
序列化与类型
- PropertyAccess — Read/write objects and arrays via string paths () → reference
foo.bar[baz] - 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
- PropertyAccess —— 通过字符串路径()读写对象和数组属性 → 参考文档
foo.bar[baz] - PropertyInfo —— 属性元数据提取(类型、访问权限、描述) → 参考文档
- TypeInfo —— PHP类型提取、解析与验证 → 参考文档
- VarDumper —— 支持HTML/CLI格式化的增强型变量调试工具 → 参考文档
- VarExporter —— 将PHP数据导出为OPcache优化代码、生成延迟加载鬼对象/代理对象 → 参考文档
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
- BrowserKit —— 模拟浏览器,支持编程式HTTP请求、Cookie、历史记录 → 参考文档
- DomCrawler —— HTML/XML遍历、CSS选择器、表单自动化 → 参考文档
- CssSelector —— 用于DOM查询的CSS到XPath转换工具 → 参考文档
- PHPUnit Bridge —— 弃用提示、时间/DNS模拟、并行测试 → 参考文档
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
- Uid —— UUID(v1-v8)和ULID生成、转换、Doctrine集成 → 参考文档
- Clock —— 可测试的时间抽象,支持MockClock和DatePoint → 参考文档
- Intl —— 国际化数据(语言、国家、货币、时区) → 参考文档
- JsonPath —— 针对JSON结构的RFC 9535标准JSONPath查询工具 → 参考文档
- Mime —— 用于邮件和内容类型的MIME消息创建工具 → 参考文档
- Ldap —— LDAP/Active Directory连接、查询与管理工具 → 参考文档
- Asset —— Web静态资源的URL生成与版本控制 → 参考文档
Quick Patterns
快速示例
Dependency Injection (Autowiring)
依赖注入(自动装配)
yaml
undefinedyaml
undefinedservices.yaml — most services are autowired automatically
services.yaml — 大多数服务会自动完成装配
services:
_defaults:
autowire: true
autoconfigure: true
App:
resource: '../src/'
exclude: '../src/{DI,Entity,Kernel.php}'
undefinedservices:
_defaults:
autowire: true
autoconfigure: true
App:
resource: '../src/'
exclude: '../src/{DI,Entity,Kernel.php}'
undefinedDefine a Route + Controller
定义路由+控制器
php
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");
}
}php
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)
分发消息(异步)
php
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()));
}
}php
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
创建并验证表单
php
$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');
}php
$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
带标签缓存
php
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']);php
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
命令行命令
php
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;
}
}php
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
事件订阅器
php
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
}
}php
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [OrderPlacedEvent::class => 'onOrderPlaced'];
}
public function onOrderPlaced(OrderPlacedEvent $event): void
{
// 处理事件
}
}Workflow Transition
工作流流转
php
if ($workflow->can($article, 'publish')) {
$workflow->apply($article, 'publish');
}php
if ($workflow->can($article, 'publish')) {
$workflow->apply($article, 'publish');
}Lock a Resource
资源加锁
php
$lock = $factory->createLock('pdf-generation', ttl: 30);
if ($lock->acquire()) {
try {
generatePdf();
} finally {
$lock->release();
}
}php
$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 () over raw PSR-6 for stampede prevention
$cache->get() - 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
- 面向PHP 8.3+和Symfony 7.x开发,启用严格类型
- 路由、命令、消息处理器、事件监听器优先使用属性声明,而非YAML/XML配置
- 优先使用自动装配,仅当需要特殊配置时才手动注册服务
- 优先使用缓存契约()而非原生PSR-6实现,避免惊群问题
$cache->get() - 应用验证分组来支持多场景表单验证需求
- 默认使用状态机,仅当需要并行状态时才使用工作流
- 针对无法用内置约束实现的业务逻辑,创建自定义验证器
- 测试中使用PHPUnit Bridge模拟时间和DNS,保证测试结果确定性