2012-02-29 120 views
16

我目前正在編寫一個通訊工具,因此必須在通過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); 

回答

26

你能做到這樣:

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

作品像它應該。謝謝:) – stoefln 2012-03-01 10:55:39

+0

我還需要這個功能,因爲它可能在我創建了一個包的許多網站中需要: http://packagist.org/packages/frosas/base-url-bundle – 2012-07-14 22:42:39

+3

您可以在全局在'''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

1

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

13

由於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

+1

這似乎不適用於Symfony 3。你會碰巧知道它是否應該在SF3中工作嗎? – conradkdotcom 2016-02-04 12:06:20

+0

事實上,這在SF3中的工作,但它不是app/config/parameters.yml,而是app/config/services.yml – LedZelkin 2017-12-11 20:19:10