Symfony2:如何在CLI脚本中设置主机/基础URL

20

我目前正在编写一款新闻通讯工具,因此必须在通过cron调用的CLI脚本中生成绝对URL。

不幸的是,Symfony CLI命令并不知道我的主机/基础URL,因此路由器会使用错误的base_url生成绝对URL。它总是使用http://localhost作为基础。

有没有办法告诉路由器正确的base_url?

我的代码:

$this->container->get('router')->generate($route, $parameters, true);
3个回答

28

你可以这样做:

$host = $this->getContainer()->getParameter('host');
$this->getContainer()->get('router')->getContext()->setHost($host);

同样地,您可以设置baseurl和scheme:

$this->getContainer()->get('router')->getContext()->setScheme('https');
$this->getContainer()->get('router')->getContext()->setBaseUrl('/web');

我也需要这个功能,因为它可能在我创建的许多网站中都需要,所以我创建了一个捆绑包:http://packagist.org/packages/frosas/base-url-bundle - Francesc Rosas
3
您可以在parameters.yml中进行全局配置。这仅适用于非Web请求,因此无需担心您的“真实”路由会受到影响。参考:全局配置请求上下文 - flu

15

自 2.1 版本以来,您可以配置路由器的默认参数,这可能是最好的方法。CLI 脚本将使用这些默认参数,但 Web 请求将覆盖它们:

# app/config/parameters.yml
parameters:
    router.request_context.host: example.org
    router.request_context.scheme: https
    router.request_context.base_url: my/path

了解更多详情,请参见如何从控制台生成URL和发送电子邮件


2
这在Symfony 3中似乎不起作用。请问您是否知道它是否应该在SF3中工作? - conradkleinespel
实际上这个在SF3中可行,但不是在app/config/parameters.yml文件中而是在app/config/services.yml文件中。 - LedZelkin

1

$host = $this->container->getParameter('host'); $this->container->get('router')->getContext()->setHost($host);


这段代码用于从容器中获取参数 "host",并将其设置为路由上下文的主机。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接