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

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

I'm currently writing a newsletter tool, and therefore have to generate absolute URLs in a CLI script which is called via cron.

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

Unfortunately the Symfony CLI command does not know anything about my host/base_url, so the router generates absolute URLs with a wrong base_url. It always uses http://localhost as base.

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

Is there a way to tell the router the correct base_url?

我的代码:

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

推荐答案

你可以这样:

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

同样可以设置baseurl和scheme:

Similarly you can set baseurl and scheme:

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

相关文章