2014-09-04 36 views
0

我有一個/文件控制器,將有兩個動作:上傳和下載Zend的:如何添加/獲取URL參數傳遞給控制器​​動作

它的定義如下:

'files' => array(
    'type' => 'Segment', 
    'options' => array(
     'route' => '/files[/:action]', 
     'defaults' => array(
      'controller' => 'Application\Controller\Files', 
      'action' => 'index', 
     ), 
    ), 
), 

我想要的下載要訪問的動作,如/ files/download/1?authString = asdf。 1在這種情況下是一個fileId。

我知道我可以將路線改爲/files[/action[/:fileId]]來設置路線,如果我錯了,請糾正我,但是如何訪問downloadAction中的fileId?還有什麼我需要改變路線定義,使其工作?

回答

2

我只能改變路線/files[/action[/:fileId]]設立的路線,糾正我,如果我錯了

你沒看錯,這將是一個有效的途徑。

還有什麼我需要改變的路線定義?

如果添加了fileId作爲一個可選路線PARAM那麼你需要做downloadAction()內的一些人工檢查,以確保它被設置。

另一種解決方案是將路線分隔成兒童,這樣可以確保除非您在每條路線上都有正確的參數,否則不會匹配。

'files' => array(
    'type' => 'Segment', 
    'options' => array(
     'route' => '/files', 
     'defaults' => array(
      'controller' => 'Application\Controller\Files', 
      'action' => 'index', 
     ), 
    ), 
    'may_terminate' => true, 
    'child_routes' => array(

     'download' => array(
      'type' => 'Segment', 
      'options' => array(
       'route' => '/download/:fileId', 
       'defaults' => array(
        'action' => 'download', 
       ), 
       'constraints' => array(
        'fileId' => '[a-zA-Z0-9]+', 
       ), 
      ), 
     ), 

     'upload' => array(
      'type' => 'Literal', 
      'options' => array(
       'route' => '/upload', 
       'defaults' => array(
        'action' => 'upload', 
       ), 
      ), 
     ), 

    ), 
), 

我怎麼訪問fileIddownloadAction

裏面最簡單的方法是將use the Zend\Mvc\Controller\Plugin\Params controller plugin來去路線參數)。

// FilesController::downloadAction() 
$fileId = $this->params('fileId'); 

或者專門從航線

// FilesController::downloadAction() 
$fileId = $this->params()->fromRoute('fileId'); 
+0

感謝一個非常清晰和完整的答案。 – Bogdan 2014-09-04 13:18:03

相關問題