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


Symfony2: how to set the host/base url in CLI scripts

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

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

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

我的代码:

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

你可以这样做:

$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');

由于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和发送电子邮件

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