Symfony Console命令需创建类(名以Command结尾、继承Command)、显式注册、configure中声明参数选项、execute返回Command::SUCCESS/FAILURE;布尔选项判null须用===true,依赖必须构造注入,禁用getContainer()。

安装完 Symfony 后,Console 命令行工具不是“装完就能用”,而是需要创建命令类、注册并调用——它是一套结构化机制,不是直接写个 PHP 脚本就执行。
确认 bin/console 可运行
进入项目根目录,先验证基础环境:
- 执行 php bin/console list —— 应列出所有内置命令(如 cache:clear、make:controller 等)
- 若报错 “Command 'console' not found” 或权限问题,检查 bin/console 是否有可执行权限(Linux/macOS 运行 chmod +x bin/console)
- Windows 用户确保已配置 PHP 解释器路径,且未误用 cmd 的旧版脚本(推荐用 Git Bash 或 PowerShell)
快速创建一个可用命令
在 src/Command/ 下新建文件,例如 src/Command/HelloCommand.php:
- 类名必须以 Command 结尾(如 HelloCommand)
- 继承 Symfony\Component\Console\Command\Command
- 设置 protected static $defaultName = 'app:hello'(冒号分隔,不用短横线)
- configure() 中调用 $this->setDescription('...') 和可选的 addArgument()/addOption()
- execute() 返回 Command::SUCCESS 或 Command::FAILURE,别 return 0/1
传参与选项的正确写法
命令逻辑跑通后,参数和选项容易出错,关键点如下:
- 必需参数需在 configure() 显式声明:$this->addArgument('name', InputArgument::REQUIRED),否则 $input->getArgument('name') 永远是 null
- 布尔选项(如 --dry-run)默认值是 null,判断时写 $input->getOption('dry-run') === true,不要用 empty() 或 !
- 带空格的值(如用户名 “John Doe”)必须加引号:php bin/console app:hello "John Doe"
- 选项设默认值:第 5 个参数才是,默认说明文案是第 4 个(空字符串也得写):$this->addOption('timeout', null, InputOption::VALUE_REQUIRED, 'Timeout in seconds', 30)
依赖注入与安全调用
CLI 环境没有请求上下文,很多 Web 服务不可用:
- 依赖必须通过构造函数注入(如 private UserRepository $userRepository),禁止在 execute() 里调 $this->getContainer()
- 数据库操作建议用 EntityManagerInterface 类型提示,避免硬编码服务 ID
- 别调 RequestStack、SessionInterface 等 HTTP 相关服务,会直接抛 LogicException
- 日志记录可用 LoggerInterface,输出信息用 $output->writeln('✅ Done.')

















