19

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);
j0k
  • 22,600
  • 28
  • 79
  • 90
stoefln
  • 14,498
  • 18
  • 79
  • 138

3 Answers3

28

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');
Saidul Islam
  • 504
  • 5
  • 6
  • I also needed this functionality and as it is probably needed in many sites I've created a bundle: http://packagist.org/packages/frosas/base-url-bundle – Francesc Rosas Jul 14 '12 at 22:42
  • 3
    You can configure this globally in the ```parameters.yml```. It will only be taken for non-web requests so no need to worry about your "real" routes being affected by this. Reference: [Configuring the Request Context globally](http://symfony.com/doc/2.3/cookbook/console/sending_emails.html#configuring-the-request-context-globally). – flu May 19 '14 at 10:46
15

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

Corneliu
  • 1,110
  • 1
  • 10
  • 16
1

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

Gara
  • 627
  • 4
  • 13