Symfony2:如何在CLI脚本中设置主机/基址url
我目前正在编写一个通讯工具,因此必须在通过cron调用的CLI脚本中生成绝对URL。Symfony2:如何在CLI脚本中设置主机/基址url
不幸的是,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和方案:
$this->getContainer()->get('router')->getContext()->setScheme('https');
$this->getContainer()->get('router')->getContext()->setBaseUrl('/web');
$host = $this->container->getParameter('host'); $this->container->get('router')->getContext()->setHost($host);
由于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
有关详细信息,请参阅How to Generate URLs and Send Emails from the Console
这似乎不适用于Symfony 3。你会碰巧知道它是否应该在SF3中工作吗? – conradkdotcom 2016-02-04 12:06:20
事实上,这在SF3中的工作,但它不是app/config/parameters.yml,而是app/config/services.yml – LedZelkin 2017-12-11 20:19:10
作品像它应该。谢谢:) – stoefln 2012-03-01 10:55:39
我还需要这个功能,因为它可能在我创建了一个包的许多网站中需要: http://packagist.org/packages/frosas/base-url-bundle – 2012-07-14 22:42:39
您可以在全局在'''parameters.yml'''中。它只会用于非网络请求,因此不必担心您的“真实”路线会受到此影响。参考:[全局配置请求上下文](http://symfony.com/doc/2.3/cookbook/console/sending_emails.html#configuring-the-request-context-globally)。 – flu 2014-05-19 10:46:27