在 Symfony 任务中使用路由生成 URL [英] Using routes to generate URLs in a Symfony task

查看:23
本文介绍了在 Symfony 任务中使用路由生成 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ubuntu 10.0.4 LTS 上运行 Symfony 1.3.6.

I am running Symfony 1.3.6 on Ubuntu 10.0.4 LTS.

我编写了一个 Symfony 任务来生成一个包含链接(URL)的报告.

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

这是我的任务类中的 execute() 方法的片段:

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); 
  }

路由名称定义如下:

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

运行时,生成的链接为:

When this is run, the generated link is:

第 1 行 产生此输出:

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

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

而不是预期:

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

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

第 2 行 生成错误:

无法找到匹配的路线为参数数组('动作' => 'symfony', '模块' =>'.',)".

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

同样,预期的 URL 是:

Again, the expected URL is:

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

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

我该如何解决这个问题?

How may I resolve this?

推荐答案

在任务中生成 URL:

To generate a URL in a task:

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

我们添加了一个生成路由的方法,以便始终使用生产 URL:

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;
  }

这篇关于在 Symfony 任务中使用路由生成 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆