symfony
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 — 服务容器、自动装配、编译器传递、标记服务 → 参考文档
- Contracts — 用于互操作性的解耦抽象(缓存、事件调度器、HTTP客户端等) → 参考文档
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 — 基于RFC 9535标准的JSON结构查询 → 参考文档
- 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,以获得可预测的测试结果