路由问题,基于URL中的变量的调用控制器-Laravel 4 [英] Routing Issue, Calling Controller based on Variables in URL- Laravel 4

查看:52
本文介绍了路由问题,基于URL中的变量的调用控制器-Laravel 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4开发应用程序,我需要做的是: 假设我有以下路线:

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',

  );

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

Inside it I need to decide based on the entity variable which Controller and method should be called for example:

 'MyNameSpace\MyPackage\StudentController@methodname'

如果

entity == Student 

并致电

  'MyNameSpace\MyPackage\StaffController@methodname'

如果

    entity == Staff

如何在Laravel 4路由中完成路由,还是我必须想出2条不同的路由?

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')

推荐答案

这应该符合您的需求

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

这篇关于路由问题,基于URL中的变量的调用控制器-Laravel 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆