Php 如何在Laravel 4.1中调用控制器操作并执行过滤器
所以这个标题很好地描述了我的问题,我想,但让我解释一下为什么我想这样做,因为我的问题可能还有其他解决方案,我还没有考虑过 假设我有一条路由,指定它将修补的对象的类:Php 如何在Laravel 4.1中调用控制器操作并执行过滤器,php,laravel,laravel-4,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
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)可以很容易地做到这一点编码>但这样做不会调用控制器上设置的过滤器
我可以用Laravel4.0通过callAction
方法来实现,通过应用程序及其路由器,但是现在该方法已更改,并且在控制器Dispatcher
类中调用过滤器,而不是在控制器
类中调用过滤器。如果您为类声明了路由,则可以使用类似的方法:
$request = Request::create('car/update', 'POST', array('id' => 10));
return Route::dispatch($request)->getContent();
Route::get('someurl', array('before' => 'aFilter:a_parameter', 'uses' => 'someClass'));
在这种情况下,您必须在routes.php
文件中声明:
Route::post('car/update/{id}', 'CarController@update');
如果您使用这种方法,那么过滤器将自动执行
您也可以这样调用任何筛选器(未测试
,但应该可以工作):
如果过滤器返回任何响应,则$response
将包含该响应,此处过滤器参数数组
是过滤器的参数(如果使用了任何响应),例如:
Route::filter('aFilter', function($route, $request, $param){
// ...
});
如果您有这样的路线:
$request = Request::create('car/update', 'POST', array('id' => 10));
return Route::dispatch($request)->getContent();
Route::get('someurl', array('before' => 'aFilter:a_parameter', 'uses' => 'someClass'));
然后,a_参数
将在您的a过滤器
操作的$param
变量中可用。因此,我可能已经找到了解决问题的方法,它可能不是最好的解决方案,但可以工作。不要犹豫,提出一个更好的解决方案
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);
}
));
这需要我编写Route::post('car/update/{id}','CarController@update');代码>用于我拥有的所有不同类型的对象。我错了吗?对于第一个,是的,你必须为每一个声明路由。但这就是我的重点,我有许多不同的对象模型,它们有相同的路由({class}/update例如)我不想把它们都写在routes.php
文件中。你有没有试过Route::callRouteFilte
?我想我可能已经找到了解决问题的方法,我不知道它是不是很干净。如果您想告诉我您对该解决方案的看法,请参阅我的答案!谢谢