我沒有測試過這個確切的代碼,但我用類似的東西,它的工作:
Route::any('auth/{action}', function($action){
$controller = new UserController();
$controller->$action();
});
你可能會發現你還需要處理的參數,如:
Route::any('auth/{action}/{param}', function($action, $param){
$controller = new UserController();
$controller->$action($param);
});
你甚至可以調整它覆蓋所有的控制器:
Route::any('{controller}/{action?}/{param?}', function($controller,$action='index',$param=null)
{
$controller = str_replace(' ', '', ucwords(str_replace('-', ' ', $controller))).'Controller';
$controller = new $controller;
$action = lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $action))));
return $controller->$action($param);
});
如果你想有一個指數acti上一個參數,這是行不通的,但否則,它似乎工作得很好。如果你想這樣做,它也不會處理第二個參數。
很多方法可以擴展這個想法。
Jason的回答更爲正確(匹配文檔,更簡潔的代碼等),但如果您不想考慮HTTP方法,或者您想要一種主路由來處理幾乎所有的請求,這是一個選項。
確定,工作得很好,除了我不能在網址中使用參數。你的建議是什麼?據我所知,這在REST API中至關重要,有可能調用類似/ api/item/1或東西的東西。好吧,我想我必須在這種情況下使用Route ::資源。我是對的還是應該使用Route :: controller並以某種方式傳遞參數? –