动态调用控制器 [英] Calling controllers dynamically
问题描述
我正在尝试在Laravel中为我的控制器创建动态路由-我知道这可以在Kohana中完成,但是我一直未能成功使其与Laravel一起使用.
I'm attempting to create dynamic routing in Laravel for my controllers - I know this can be done in Kohana, but I've been unsuccessful trying to get it working with Laravel.
这就是我现在拥有的:
Route::get('/{controller}/{action?}/{id?}'...
所以我想打电话给controller/method($id)
.
理想情况下,这就是我想做的:
Ideally this is what I would like to do:
Route::get('/{controller}/{action?}/{id?}', $controller . '@' . $action);
并动态调用$ controller :: $ action.
And have it dynamically call $controller::$action.
我尝试这样做:
Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
$controller = new $controller();
$controller->$action();
});
但是我收到一条错误消息:类控制器不存在. 因此,当控制器扩展BaseController时,Laravel似乎并未包括所有必需的文件.
But I get an error message: Class Controller does not exist. So it appears that Laravel is not including all the necessary files when the controller extends the BaseController.
如果我使用$controller::$action()
,它告诉我不能静态调用非静态函数.
If I use $controller::$action()
it tells me I can't call a non-static function statically.
关于如何实现这项工作的任何想法?
Any ideas for how to make this work?
推荐答案
在阅读了Laravel不再支持该方法之后,我想到了以下解决方案:
After reading that Laravel doesn’t support this anymore, I came up with this solution:
$uri = $_SERVER['REQUEST_URI'];
$results = array();
preg_match('#^\/(\w+)?\/?(\w+)?\/?(\w+)?\/?#', $_SERVER['REQUEST_URI'], $results);
// set the default controller to landing
$controller = (empty($results[1])) ? 'landing' : $results[1];
// set the default method to index
$method = (empty($results[2])) ? 'index' : $results[2];
Route::get('{controller?}/{action?}/{id?}', $controller . '@' . $method);
// now we just need to catch and process the error if no controller@method exists.
这篇关于动态调用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!