Sia*_*osh 0 php laravel laravel-4 laravel-routing
我正在用Laravel 4开发一个应用程序我需要做的是:让我说我有以下路线:
Route::get('/myroute/{entity}/methodname',
);
Run Code Online (Sandbox Code Playgroud)
在其中我需要根据实体变量来决定应该调用哪个Controller和方法,例如:
'MyNameSpace\MyPackage\StudentController@methodname'
Run Code Online (Sandbox Code Playgroud)
如果
entity == Student
Run Code Online (Sandbox Code Playgroud)
并打电话给
'MyNameSpace\MyPackage\StaffController@methodname'
Run Code Online (Sandbox Code Playgroud)
如果
entity == Staff
Run Code Online (Sandbox Code Playgroud)
如何在Laravel 4中完成路由是否有可能或者我必须想出两条不同的路线呢?
Route::get('/myroute/Student/methodname') and Route::get('/myroute/Staff/methodname')
Run Code Online (Sandbox Code Playgroud)
这应该符合您的需要
Route::get('/myroute/{entity}/methodname', function($entity){
$controller = App::make('MyNameSpace\\MyPackage\\'.$entity.'Controller');
return $controller->callAction('methodname', array());
}
Run Code Online (Sandbox Code Playgroud)
现在为了避免错误,我们还要检查控制器和操作是否存在:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
要使流程自动化一点,您甚至可以使动作名称动态化
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1488 次 |
| 最近记录: |