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

↘锁芯ラ 提交于 2019-12-20 09:37:06

问题


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

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.

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

My code:

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

回答1:


You can do it in this way:

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

Similarly you can set baseurl and scheme:

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



回答2:


Since 2.1 you can configure the default parameters of the router, which is probably the best approach. A CLI script will use these default parameters, however a web request will override them:

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

For more details, see How to Generate URLs and Send Emails from the Console




回答3:


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



来源:https://stackoverflow.com/questions/9503250/symfony2-how-to-set-the-host-base-url-in-cli-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!