如何在Laravel 4.1中调用控制器操作并执行过滤器

时间:2014-04-16 17:20:59

标签: php laravel laravel-4

所以标题很好地描述了我的问题,但是让我解释一下为什么我要这样做,因为我可能还有另一个解决我问题的方法,我没想过。

假设我有一个路由指定它将修补的对象的类:

Route::patch('{class}/{id}', array(
  'as' => 'object.update',
  function ($class, $id) {
    $response = ...; 
    // here I want to call the update action of the right controller which will
    // be named for instance CarController if $class is set to "car")
    return $response;
  }
));

使用$app->make($controllerClass)->callAction($action, $parameters);这很容易,但这样做不会调用控制器上设置的过滤器

我能够使用laravel 4.0和callAction方法,传递应用程序及其路由器,但是现在方法已经改变,并且在ControllerDispatcher类中调用过滤器而不是Controller上课。

2 个答案:

答案 0 :(得分:1)

如果您为类声明了路线,那么您可以使用以下内容:

$request = Request::create('car/update', 'POST', array('id' => 10));
return Route::dispatch($request)->getContent();

在这种情况下,您必须在routes.php文件中声明:

Route::post('car/update/{id}', 'CarController@update');

如果使用此方法,则会自动执行过滤器。

你也可以调用任何这样的过滤器(not tested但是应该工作IMO):

$response = Route::callRouteFilter('filtername', 'filter parameter array', Route::current(), Request::instance());

如果您的过滤器返回任何响应,那么$response将包含该响应,此处filter parameter array是过滤器的参数(如果有任何使用过的话),例如:

Route::filter('aFilter', function($route, $request, $param){
    // ...
});

如果你有这样的路线:

Route::get('someurl', array('before' => 'aFilter:a_parameter', 'uses' => 'someClass'));

然后,您a_parameter过滤器操作中的$param变量中会显示aFilter

答案 1 :(得分:1)

所以我可能已经找到了解决问题的方法,它可能不是最好的解决方案,但它有效。不要犹豫,提出更好的解决方案!

Route::patch('{class}/{id}', array(
  'as' => 'object.update',
  function ($class, $id) {
    $router = app()['router']; // get router
    $route = $router->current(); // get current route
    $request = Request::instance(); // get http request
    $controller = camel_case($class) . 'Controller'; // generate controller name
    $action = 'update'; // action is update

    $dispatcher = $router->getControllerDispatcher(); // get the dispatcher

    // now we can call the dispatch method from the dispatcher which returns the
    // controller action's response executing the filters
    return $dispatcher->dispatch($route, $request, $controller, $action);
  }
));
相关问题