繁体   English   中英

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

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

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

不幸的是,Symfony CLI命令对我的host / 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM