1

在 Bolt 扩展中,我有很多路由绑定到应用程序的实例,如下所示:

$this->app->post(Extension::API_PREFIX . "session", array($this, 'login'))
              ->bind('login');
$this->app->delete(Extension::API_PREFIX . "session", array($this, 'logout'))
              ->bind('logout');


$this->app->post(Extension::API_PREFIX . "resetpassword", array($this, 'reset_password'))
              ->bind('reset_password');

$this->app->post(Extension::API_PREFIX . "forgotpassword", array($this, 'forgot_password'))
              ->bind('forgot_password');

$this->app->post(Extension::API_PREFIX . "changepassword", array($this, 'change_password'))
              ->bind('change_password');

$this->app->get(Extension::API_PREFIX . "session", array($this, 'get_session'))
              ->bind('get_session');

但我想对before路由的子集运行过滤器。如何将其中一些路由组合在一起并绑定过滤器?到目前为止,我只发现了如何在所有路由上使用过滤器,如下所示:

$this->app->before(function (Request $request) {    
    // Filter request here
 });
4

1 回答 1

3

ControllerCollection 类将它的调用转发到它持有的每个控制器。所以你可以做类似(未经测试的代码!):

<?php
// intializations, etc.

// this will give you a new ControllerCollection class
$collection = $this->app['controllers_factory'];

$collection->post(Extension::API_PREFIX . "session", array($this, 'login'))
           ->bind('login');
// etc.

// Apply middleware:
$collection->before(function(Request $request) {
  // do whatever you want in your filter
});

// Mount the collection to a certain URL:
$this->app->mount('/mount-point', $collection);  // if you don't want /mount-point 
                                                 // just pass an empty string

请注意,这仅在您将所有路由放在相同的 PATH 下才有效,因为您需要“挂载”集合以启用路由(您已经使用Extension::API_PREFIX

于 2015-03-20T07:23:46.943 回答