Using routes to generate URLs in a Symfony task

morpheous picture morpheous · Jul 20, 2010 · Viewed 15k times · Source

I am running Symfony 1.3.6 on Ubuntu 10.0.4 LTS.

I have written a Symfony task that generates a report which contains links (URLs).

Here is a snippet of the execute() method in my task class:

  protected function execute($arguments = array(), $options = array())
  {
    //create a context
    sfContext::createInstance($this->configuration);
    sfContext::getInstance()->getConfiguration()->loadHelpers(array('Url', 'Asset', 'Tag'));

    ...
    $url = url_for("@foobar?cow=marymoo&id=42");

    // Line 1
    echo '<a href="'.$url.'">This is a test</a>';

    // Line 2
    echo link_to('This is a test', $url); 
  }

The route name is defined like this:

foobar:
  url: /some/fancy/path/:cow/:id/hello.html
  param: {  module: mymodule, action: myaction }

When this is run, the generated link is:

Line 1 produces this output:

./symfony/symfony/some/fancy/path/marymoo/42/hello.html

instead of the expected:

/some/fancy/path/marymoo/42/hello.html

Line 2 generates an error:

Unable to find a matching route to generate url for params "array ( 'action' => 'symfony', 'module' => '.',)".

Again, the expected URL is:

/some/fancy/path/marymoo/42/hello.html

How may I resolve this?

Answer

Jeremy Kauffman picture Jeremy Kauffman · Jul 20, 2010

To generate a URL in a task:

protected function execute($arguments = array(), $options = array())
{
  $routing = $this->getRouting();
  $url = $routing->generate('route_name', $parameters);
}

We add a method to generate routing so that the production URL is always used:

   /**
   * Gets routing with the host url set to the url of the production server
   * @return sfPatternRouting
   */
  protected function getProductionRouting()
  {
    $routing = $this->getRouting();
    $routingOptions = $routing->getOptions();
    $routingOptions['context']['host'] = 'www.example.com';
    $routing->initialize($this->dispatcher, $routing->getCache(), $routingOptions);
    return $routing;
  }