在Bolt扩展中,我有很多绑定到App实例的路由,如下所示:
$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
});
答案 0 :(得分:3)
ControllerCollection class forwards its calls to each of the controllers it holds。所以你可以做一些像(未经测试的代码!):
<?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
请注意,这只有在您将所有路径放在同一路径下所需的“路由”集合以启用路由时才会起作用(您已经使用Extension::API_PREFIX
)