2013-06-25 41 views
0

我目前有一個看起來像這樣的段路由:/shop/:shopId/其中shopId沒有默認值。在ZF2路由器中注入默認值

只要路由匹配,Module.php中的代碼就會被觸發,它會根據shopId做一些準備並將其保存在會話中。

我的問題是,如果有可能的話,在這一點上,設置路線的默認值爲shopId?最終目標是能夠組裝URL,而不必每次都指定shopId

我記得在ZF1中這個行爲是默認的,在組裝URL的時候,請求中的匹配參數被重用,並且你必須明確地指定你希望它們被刪除。現在我需要相同的功能,但在Module.php級別配置,而不必重寫每個assemble()調用。

回答

1

選項之一:從您的indexAction

$id = $routeMatch->getParam('id', false); 
if (!$id) 
    $id = 1; // id was not supplied set default one note this can be added as constant or from db .... 

選擇二:在module.config.php

'product-view' => array(
       'type' => 'Literal', 
       'options' => array(
        'route' => '/product/view', 
        'defaults' => array(
         'controller' => 'product-view-controller', 
         'action'  => 'index', 
        ), 
       ), 
       'may_terminate' => true, 
       'child_routes' => array(
        'default' => array(
         'type' => 'Segment', 
         'options' => array(
          'route' => '[/:cat][/]', 
          'constraints' => array(
           'cat'  => '[a-zA-Z][a-zA-Z0-9_-]*', 
          ), 
          'defaults' => array(
          ), 
         ), 
        ), 
       ), 
      ), 

設定路線你控制器:

public function indexAction() 
    { 
     // get category param 
     $categoryParam = $this->params()->fromRoute('cat'); 
     // if !cat then get random category 
     $categoryParam = ($categoryParam) ? $categoryParam : $this->categories[array_rand($this->categories)]; 
     $shortList = $this->listingsTable->getListingsByCategory($categoryParam); 
     return new ViewModel(array(
      'shortList' => $shortList, 
      'categoryParam' => $categoryParam 
     )); 
    }