如何使用 symfony 在控制台中生成 SERVER_NAME?

How to generate the SERVER_NAME in a console with symfony?

我想编写一个脚本来向用户发送通知邮件并每小时执行一次,我希望它与托管 symfony 站点的服务器名称相匹配。我已经尝试使用 $_SERVER,但它没有定义,this post 上的解决方案但是控制台没有请求,所以它确实有效。

由于在控制台命令中没有传统的 'web request/response' 东西,您在 twig 或 $this->generateUrl('...') 或类似的 controllers/services´ 中使用 {{ path('...') }} 生成的所有 URL 可能是http://localhost/...

要解决这个问题,只需添加:(如果您使用的是 symfony 5.1+)

# config/packages/routing.yaml
framework:
    router:
        # but you should move it to your .env file and user two differen env-variables for host and scheme
        default_uri: 'https://you-site-hostname.com/'

或者如果您使用的是旧版本,请将 router.request_context.schemerouter.request_context.host 给你参数。喜欢

# config/services.yaml
parameters:
    router.request_context.scheme: 'https'
    asset.request_context.host: 'you-site-hostname.com'

看这里:https://symfony.com/doc/current/routing.html#generating-urls-in-commands

这里(我的个人建议)https://symfonycasts.com/screencast/mailer/route-context