2017-09-12 118 views
0

在我模塊的module.config.php,我有這樣的事情:ZF3:如何根據方法和路線路由到特定控制器/操作?

namespace Application; 

return [ 
    //... 
    // myroute1 will route to IndexController fooAction if the route is matching '/index/foo' but regardless of request method 
    'myroute1' => [ 
     'type' => Zend\Router\Http\Literal::class, 
     'options' => [ 
      'route' => '/index/foo', 
      'defaults' => [ 
       'controller' => Controller\IndexController::class, 
       'action'  => 'foo', 
      ], 
     ], 
    ], 

    // myroute2 will route to IndexController fooAction if the route is request method is GET but regardless of requested route 
    'myroute2' => [ 
     'type' => Zend\Router\Http\Method::class, 
     'options' => [ 
      'verb'  => 'get', 
      'defaults' => [ 
       'controller' => Controller\IndexController::class, 
       'action'  => 'foo', 
      ], 
     ], 
    ], 
    //... 
]; 

我想要實現:

  • 如果路線/索引/富請求,並通過要求GET方法,那麼它應該被路由到IndexControllerfooAction
  • 如果r歐特/索引/富請求,並通過POST法的要求,那麼它應該被路由到的IndexController酒吧行動(注意到它的barAction這裏沒有fooAction)

如何實現那?

回答

2

在心裏告訴自己看到和其他人看,作爲附加的註釋爲@ delboy1978uk的答案。

我一直在尋找的答案是這樣的:

  • GET /index/foo =>索引控制器fooAction
  • POST /index/foo =>索引控制器barAction

所以在module.config.php文件中的代碼可像這樣:

return [ 
    //... 
    'myroute1' => [// The parent route will match the route "/index/foo" 
     'type' => Zend\Router\Http\Literal::class, 
     'options' => [ 
      'route' => '/index/foo', 
      'defaults' => [ 
       'controller' => Controller\IndexController::class, 
       'action'  => 'foo', 
      ], 
     ], 
     'may_terminate' => false, 
     'child_routes' => [ 
      'myroute1get' => [// This child route will match GET request 
       'type' => Method::class, 
       'options' => [ 
        'verb' => 'get', 
        'defaults' => [ 
         'controller' => Controller\IndexController::class, 
         'action'  => 'foo' 
        ], 
       ], 
      ], 
      'myroute1post' => [// This child route will match POST request 
       'type' => Method::class, 
       'options' => [ 
        'verb' => 'post', 
        'defaults' => [ 
         'controller' => Controller\IndexController::class, 
         'action'  => 'bar' 
        ], 
       ], 
      ] 
     ], 
    ], 
    //... 
]; 
+0

你剛剛節省了我的時間。禮炮! –

相關問題