Calling controllers dynamically

怎甘沉沦 提交于 2020-01-15 12:30:08

问题


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.

This is what I have right now:

Route::get('/{controller}/{action?}/{id?}'...

So I would like to call controller/method($id) with that.

Ideally this is what I would like to do:

Route::get('/{controller}/{action?}/{id?}', $controller . '@' . $action);

And have it dynamically call $controller::$action.

I've tried doing this:

Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
    $controller = new $controller();
    $controller->$action();
});

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.

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?


回答1:


You can auto register all controllers in one fell swoop:

Route::controller( Controller::detect() );

If you're using Laravel 4 (as your tag implies), you can't use Controller::detect() anymore. You'll have to manually register all the controllers you want to use.




回答2:


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.


来源:https://stackoverflow.com/questions/17159683/calling-controllers-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!