如何在Symfony控制台环境中生成SERVER_NAME?
Symfony控制台脚本统一SERVER_NAME配置方案
CLI模式下无HTTP请求上下文,因此$_SERVER变量和请求对象均无法使用,可通过全局统一配置的方式保证Web和控制台场景的域名一致性,具体操作步骤如下:
1. 配置全局域名参数
- 优先通过环境变量管理适配多环境差异,在项目.env文件(如
.env.local)添加站点域名配置:
SITE_DOMAIN=your-official-domain.com
- 打开
config/services.yaml在参数区块绑定环境变量为全局容器参数:
parameters: # 该参数在Web和CLI场景下均可正常读取 site.server_name: '%env(SITE_DOMAIN)%'
如果是单环境项目也可以直接在parameters里写死域名值,无需走环境变量。
2. 编写定时发送邮件的控制台命令
- 执行生成命令创建自定义控制台类:
php bin/console make:command SendHourlyNotificationEmail - 在生成的命令类中注入全局参数编写业务逻辑,示例代码如下:
<?php // src/Command/SendHourlyNotificationEmailCommand.php namespace App\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Email; class SendHourlyNotificationEmailCommand extends Command { protected static $defaultName = 'app:send-hourly-notice'; protected static $defaultDescription = '每小时批量发送用户通知邮件'; public function __construct( private MailerInterface $mailer, // 注入我们配置的全局SERVER_NAME参数 private string $siteServerName ) { parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { // 此处替换为你实际的待通知用户查询逻辑 $notifyUsers = []; foreach ($notifyUsers as $user) { $email = (new Email()) ->from('system@'.$this->siteServerName) ->to($user->getEmail()) ->subject('站点新通知提醒') ->html(sprintf('<p>请访问站点查看详情:<a href="https://%s">%s</a></p>', $this->siteServerName, $this->siteServerName )); $this->mailer->send($email); } $output->writeln('通知邮件发送完毕,共发送'.count($notifyUsers).'封'); return Command::SUCCESS; } }
3. 配置每小时执行的定时任务
- 编辑服务器crontab规则,添加定时执行配置:
0 * * * * /usr/bin/php /你的项目绝对路径/bin/console app:send-hourly-notice >> /var/log/symfony_notice_email.log 2>&1
注意替换PHP执行路径、项目路径为服务器实际值,日志路径也可自行调整。
内容的提问来源于stack exchange,提问作者Fabien Julio
相关产品推荐
相关产品推荐

