路由问题,基于URL-Laravel 4中的变量调用控制器

时间:2014-11-05 14:04:09

标签: php laravel laravel-4 laravel-routing

我正在使用Laravel 4开发一个应用程序,我需要做的是: 让我们说我有以下路线:

  Route::get('/myroute/{entity}/methodname',

  );

在其中我需要根据实体变量决定应该调用哪个Controller和方法,例如:

 'MyNameSpace\MyPackage\StudentController@methodname'

如果

entity == Student 

并致电

  'MyNameSpace\MyPackage\StaffController@methodname'

如果

    entity == Staff

如何在Laravel 4中完成路由是否有可能或者我必须想出两条不同的路线呢?

    Route::get('/myroute/Student/methodname') and Route::get('/myroute/Staff/methodname')

1 个答案:

答案 0 :(得分:6)

这应该符合您的需要

Route::get('/myroute/{entity}/methodname', function($entity){
    $controller = App::make('MyNameSpace\\MyPackage\\'.$entity.'Controller');
    return $controller->callAction('methodname', array());
}

现在为了避免错误,我们还要检查控制器和操作是否存在:

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());
    }
}

更新

要使流程自动化一点,您甚至可以将动作名称设为动态

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());
    }
}