2013-01-25 45 views
0

如果可能,我想知道是否可以基於某些參數動態地添加/註冊新路由。在Symfony1.4中添加動態路由

我知道,一個途徑是somethig像

newsdetail: 
    url: /newsdetail/:id/:title 
    class: sfDoctrineRoute 
    options: { model: News, type object } 
    param: { module: articles, action: articledetail } 
    requirements: 
     id: \d+ 
     sf_method: [get] 

但現在,是有我的方式來添加,或者附加這種路線的動作? 我的問題是,該模塊和行動可能會改變取決於網站實例...

所以,我已經建立了一個組件,做一些事情和兩個不同的模塊,假設module1和module2,兩個包括組件。 由於不同的原因,我無法在路由文件中註冊所有這些路由。 現在,用戶1必須具有去往模塊1的路線,並且用戶2必須具有模塊2的路線。 所以,我想在行動中添加路線。 我希望我更好地解釋它

+0

你是什麼意思的網站實例? – j0k

+0

爲了簡短起見,對於用戶可能是模塊新聞,anche行動articledetail,併爲其他用戶可能是模塊anothrnews和行動anotherarticledetail,取決於他們的憑據 – ilSavo

回答

1

Here is an example about building dynamic route

基本上是:

  • 你添加一個偵聽事件routing.load_configuration
  • 這個監聽器從數據庫中檢索路由,並預先考慮到當前的路由緩存

這裏是一個清潔片段:

<?php 

class frontendConfiguration extends sfApplicationConfiguration 
{ 
    public function configure() 
    { 
    $this->dispatcher->connect('routing.load_configuration', array($this, 'listenToRoutingLoadConfigurationEvent')); 
    } 

    public function listenToRoutingLoadConfigurationEvent(sfEvent $event) 
    { 
    $routing = $event->getSubject(); 
    $products = Doctrine::getTable('Product')->findAll(); 

    foreach ($products as $product) 
    { 
     if (0 == strlen($product->route)) 
     { 
     continue; 
     } 

     $name = 'product_'.$product->id; 
     $route = new sfRoute(
     $product->route, 
     array('module' => 'browse', 'action' => 'catalog', 'product' => $product->id), 
     array('product' => '\d+'), 
     array('extra_parameters_as_query_string' => false) 
    ); 

     $routing->prependRoute($name, $route); 
    } 
    } 
} 

編輯:

您可以檢索使用上下文從動作的路由:

$this->getContext()->getRouting() 

所以,如果你想從動作添加路由,您可以執行以下操作:

$route = new sfRoute(
    '/my-route', 
    array('module' => 'browse', 'action' => 'catalog', 'product' => 456), 
    array('product' => '\d+'), 
    array('extra_parameters_as_query_string' => false) 
); 

$this->getContext()->getRouting()->prependRoute('my-route', $route); 

無論如何,我仍然不會真的明白你想怎麼做...即使在你最後編輯。

+0

好的,謝謝你的片段。但是現在,我可以在模塊操作中做到這一點嗎?!或者我必須在frontendConfiguration.class.php中做到這一點? – ilSavo

+0

我認爲您需要更好地解釋您計劃如何在應用程序中更新路線,在這種情況下,針對哪些操作,用戶等等。因此,將很容易找到如何處理它。更新您的問題,而不是在下面發表評論。 – j0k

+0

好的,問題已更新。我希望我能以更好的方式解釋 – ilSavo

0

爲什麼不具有相同的路由並根據憑據更改內容?