2010-07-19 15 views
7

Estoy ejecutando Symfony 1.3.6 en Ubuntu 10.0.4 LTS.Uso de rutas para generar direcciones URL en una tarea de Symfony

He escrito una tarea de Symfony que genera un informe que contiene enlaces (URL).

Aquí hay un fragmento del método execute() en mi clase de tarea:

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

El nombre de la ruta se define así:

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

Cuando se ejecuta, el enlace generado es:

La línea 1 produce esta salida:

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

en lugar del esperado:

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

Línea 2 genera un error:

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

Una vez más, la URL esperada es:

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

¿En qué puedo resolver ¿esta?

Respuesta

17

Para generar una URL en una tarea:

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

Añadimos un método para generar el enrutamiento de manera que la URL de producción se utiliza siempre:

/** 
    * 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; 
    } 
+0

+1 por el bonito, breve fragmento que me muestra cómo resolver este problema. Voy a modificar el código ligeramente para adaptarme a lo que estoy haciendo, probarlo, si funciona, aceptaré esta respuesta. – morpheous

+0

¡Funciona !. Gracias, gracias, gracias! :) – morpheous

+0

¿Dónde debería poner este fragmento?No puedo llamar a $ this-> getRouting() desde una tarea:/ – JavierIEH

1

he tenido el mismo problema y ha encontrado el siguiente fragmento de código: http://snippets.symfony-project.org/snippet/378

La solución es bastante similar, sin embargo, amplía la ProjectConfiguration. La ventaja de este enfoque es que también funciona de manera transparente en los módulos.

3

Te quiero utilizar helpers estándares (como url_for) para generar URL, puede que este código podría ayudarle a:

protected function execute($arguments = array(), $options = array()) 
    { 
    // initialize the database connection 
... 
$context = sfContext::createInstance($this->configuration); 

$routing = $context->getRouting(); 
$_options = $routing->getOptions(); 
$_options['context']['prefix'] = "";// "/frontend_dev.php" for dev; or "" for prod 
$_options['context']['host'] = sfConfig::get('app_url_base'); 
$routing->initialize($this->dispatcher, $routing->getCache(),$_options); 
$context->getConfiguration()->loadHelpers('Partial'); 
$context->set('routing',$routing);  
//$_SERVER['HTTP_HOST'] = sfConfig::get('app_url_base'); // ---> I don't remember why I have this on my code, shouldn't be necessary 
... 

A continuación, puede utilizar url_for función todas partes con absoluta = true parámetro trabajando mágicamente.

Por supuesto, es necesario añadir una definición * * url_base en su app.yml (o tal vez se puede dejar harcoded)

+2

thansk mucho, esto funcionó para mí. pequeño comentario: '$ options' se usa para las opciones de línea de comando de la tarea, por lo que un nombre diferente para la variable evita problemas. – Tapper

+0

Actualizado. Gracias. – glerendegui

0

Se pueden ajustar las opciones de solicitud por defecto para los comandos (sfTask) en la secuencia de comandos de configuración del proyecto config/ProjectConfiguration.class.php

class ProjectConfiguration extends sfProjectConfiguration { 

    public function setup() { 
     ... 
     $this->dispatcher->connect('command.pre_command', array('TaskWebRequest', 'patchConfig')); 
    } 

} 

class TaskWebRequest extends sfWebRequest { 

    public function __construct(sfEventDispatcher $dispatcher, $parameters = array(), $attributes = array(), $options = array()) 
    { 
     $options['no_script_name'] = true; 
     $options['relative_url_root'] = ''; 
     parent::__construct($dispatcher, $parameters, $attributes, $options); 
    } 

    public static function patchConfig(sfEvent $event) { 
     sfConfig::set('sf_factory_request', 'TaskWebRequest'); 
    } 

} 
Cuestiones relacionadas