如果你没理解 Symfony 的 Service Container,你会觉得 Symfony 很“重”。
理解以后你会发现:
它不是重,而是有组织能力。
Service Container 可以看成:
全区工作人员名册
+ 部门编制表
+ 自动派工台
+ 依赖装配室比如你写一个业务服务:
<?php
namespace App\Service;
use App\Entity\BusinessPermit;
use App\Message\PermitSubmittedMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\MessageBusInterface;
final class PermitService
{
public function __construct(
private EntityManagerInterface $entityManager,
private MessageBusInterface $bus,
) {
}
public function submit(BusinessPermit $permit): void
{
$permit->markSubmitted();
$this->entityManager->persist($permit);
$this->entityManager->flush();
$this->bus->dispatch(new PermitSubmittedMessage($permit->getId()));
}
}然后控制器只做协调:
#[Route('/permits/new', name: 'permit_new', methods: ['GET', 'POST'])]
public function new(
Request $request,
PermitService $permitService
): Response {
// ...
}你并没有自己 new PermitService(...)。
这不是偷懒,而是:
派工局会根据类型提示,自动把该来的人派来。
这就是 autowiring 的价值。
它带来的不是“少写几行代码”这么简单,而是:
- 依赖关系变清晰
- 测试更容易替换实现
- 控制器、命令、消息处理器、事件订阅者都说同一种依赖语言
- 大系统里不会到处手工拼对象
调试时也很好用:
php bin/console debug:autowiring
php bin/console debug:container所以 Symfony 的容器不是装饰品。
它是整座城区“为什么不会乱成一锅”的关键。