duanshang9426 2016-05-20 09:49
浏览 19

休息api控制器

I have build a Rest webservice that has a mvc structure, but I need some suggestion on how to make it better.

What I have right know is :

all the request come to the front controller (index.php)

  $request = new Request();  //parse all the elements of the request

// spl_api_autoload takes care for loading the classes

  $controller_name = ucfirst($request->url_elements[1]) . 'Controller';

  if (class_exists($controller_name)) {
    $controller = new $controller_name();
    $action_name = strtolower($request->verb) . 'Action';
     $result = $controller->$action_name($request);

  }  // this acts like a sort of router 

The url looks like this:

index.php/tree/addnode/4/testnode

tree -> Resource

addnode -> action

4 -> parent id

testnode -> node name

What I need a suggestion is in this part down here (controller) :

 if(isset($request->url_elements[2])) {

    switch ($request->url_elements[2]) {
      case 'addroot':

      if(isset($request->url_elements[3])) {


        $name = $request->url_elements[3];


        $nested = new NestedSetClass();

        $nested->createRootNode($name);


      }
      return $data;

      break;

      case 'addnode':


      if(isset($request->url_elements[3])) {

        if(isset($request->url_elements[4])) { 

          $parent = $request->url_elements[3];

          $name = $request->url_elements[4];


          $nested = new NestedSetClass();

          $nested->insertChildNode($name,$parent);
        }
      } 
      break;
      default:
            # code...
            break;
      } 

   } 

I want to skip the switch cases , Is there anyway I can do this ?

Thank you very very much for your time

  • 写回答

1条回答 默认 最新

  • dongpao1873 2017-01-18 00:56
    关注

    When doing something like this I used the html methods like so

    $app = App::init();
    try{
       //Pass the information here so data can be handled
       //This makes it easier for other people who are new to oop, but not really correct
       $app->$method($target, $data)
    }catch(Exception e){ //handle error }
    
    App Class
    public function get($target, $data); get resource from db
    public function post($target, $data); post resource to db 
    etc.
    
    Sample of post
    function post($target, $data)
    {
         $control = new $target();
         return $control->handle($data);
    
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路