使用make:command生成命令骨架最省时可靠,自动创建src/command/下的类文件并预置configure()和execute()方法,再配置名称、参数、选项,注入服务实现逻辑,最后通过console命令验证运行。

直接用 make:command 生成骨架,再填业务逻辑,是最省时可靠的方式。只要项目装了 symfony/maker-bundle(5.4+ 默认包含),一行命令就能搞定文件位置、命名规范和基础结构。
快速生成命令类文件
在终端执行:
php bin/console make:command app:send-reminders
按提示输入类名(如 SendRemindersCommand),回车确认。Symfony 会自动创建文件 src/Command/SendRemindersCommand.php,并确保它:
- 位于
src/Command/目录下 - 类名以 Command 结尾,命名空间为 App\Command
- 继承
Symfony\Component\Console\Command\Command - 已预置
configure()和execute()方法
配置命令名称与交互说明
打开刚生成的文件,在 configure() 方法中修改:
$this->setName('app:send-reminders');
$this->setDescription('Send daily email reminders to active users.');
$this->setHelp('This command fetches users with pending tasks and dispatches reminder emails.');
还可在此处声明参数和选项,例如:
- 添加必填用户名参数:
$this->addArgument('batch-size', InputArgument::OPTIONAL, 'Number of users to process', 100); - 添加布尔型选项:
$this->addOption('dry-run', 'd', InputOption::VALUE_NONE, 'Output what would be sent without sending');
编写执行逻辑与依赖注入
在 execute() 方法中实现核心功能。推荐通过构造函数注入服务,例如:
private MailerInterface $mailer;
private EntityManagerInterface $em;
public function __construct(MailerInterface $mailer, EntityManagerInterface $em)
{
$this->mailer = $mailer;
$this->em = $em;
parent::__construct();
}
然后在 execute() 中读取参数、调用服务、输出反馈:
- 获取参数:
$batchSize = $input->getArgument('batch-size'); - 查询用户:
$users = $this->em->getRepository(User::class)->findActiveForReminder($batchSize); - 发送邮件(带 dry-run 判断):
if (!$input->getOption('dry-run')) { $this->mailer->send(...); } - 输出状态:
$output->writeln(sprintf('Sent to %d users.', count($users))); - 返回状态码:
return Command::SUCCESS;或return 1;
验证与运行命令
保存后,直接运行以下命令检查是否识别成功:
php bin/console list | grep app:
看到 app:send-reminders 即表示注册成功。试运行帮助信息:
php bin/console app:send-reminders --help
实际执行(加 --dry-run 先测试):
php bin/console app:send-reminders --dry-run
确认无误后去掉选项正式运行。











