问题
I am developing an application with Laravel 4 what I need to do is this: let's say I have the following route:
Route::get('/myroute/{entity}/methodname',
);
Inside it I need to decide based on the entity variable which Controller and method should be called for example:
'MyNameSpace\MyPackage\StudentController@methodname'
if the
entity == Student
and call the
'MyNameSpace\MyPackage\StaffController@methodname'
if the
entity == Staff
how in can be done in Laravel 4 routing is it possible at all or I have to come up with 2 different routes anyway like?
Route::get('/myroute/Student/methodname') and Route::get('/myroute/Staff/methodname')
回答1:
This should fit your need
Route::get('/myroute/{entity}/methodname', function($entity){
$controller = App::make('MyNameSpace\\MyPackage\\'.$entity.'Controller');
return $controller->callAction('methodname', array());
}
Now to avoid errors, lets also check if the controller and action exists:
Route::get('/myroute/{entity}/methodname', function($entity){
$controllerClass = 'MyNameSpace\\MyPackage\\'.$entity.'Controller';
$actionName = 'methodname';
if(method_exists($controllerClass, $actionName.'Action')){
$controller = App::make($controllerClass);
return $controller->callAction($actionName, array());
}
}
Update
To automate the process a bit more you can even make the action name dynamic
Route::get('/myroute/{entity}/{action?}', function($entity, $action = 'index'){
$controllerClass = 'MyNameSpace\\MyPackage\\'.$entity.'Controller';
$action = studly_case($action) // optional, converts foo-bar into FooBar for example
$methodName = 'get'.$action; // this step depends on how your actions are called (get... / ...Action)
if(method_exists($controllerClass, $methodName)){
$controller = App::make($controllerClass);
return $controller->callAction($methodName, array());
}
}
来源:https://stackoverflow.com/questions/26759141/routing-issue-calling-controller-based-on-variables-in-url-laravel-4