PHP中用于流控制的开关与类


Switch vs Classes for flow control in PHP

最近,我编写了一个简单的web应用程序。我现在有。

  • 一个静态页面,它提供html标记和我需要的资源
  • 一种javascript路由处理机制,它与服务器通信并在客户端上呈现响应

对于我需要操作的每个对象,服务器在/app/object.php提供一个php脚本,该脚本接受POST数据并返回JSON结果。

例如(不是实际反应):

POST /app/comments.php?a=add&page_id=43&author=A&text=Some%20Text
{"s":"OK"}
POST /app/comments.php?a=list&page_id=43
[{ "author": 'A', "text": "Some text"}, { "author": "B", "text": "Other text"}]
POST /app/users.php?a=list
["A", "B", "C"]

在后台,JSON api是这样实现的:

//comments.php
require('init.php'); 
// start sessions, open database connections with data in config.php
switch(POST('a')){
case "list":
    //.... retrieving data
    echo json_encode($data)
break;
case "add":
    //.... inserting data
    echo '{"s":"OK"}';
break;
}

最大的对象有7个方法和200个(缩进良好,未压缩)LOC,而平均每个对象大约有3个方法。

我的一位开发人员朋友建议用对象代替交换机,使其"更简单"、"更可扩展"answers"更可维护"。

坦率地说,我不认为这样的系统会变得更简单(尤其是通过使用对象),但我很想知道其他开发人员的意见。

忽略在PHP中使用对象的性能影响,我应该使用基于类的方法吗?

如果是,如何构建JSON API以使用对象,而不添加太多代码(从而降低项目的可维护性)?

<?php
class Controller {
  protected $post;
  public function __construct() {
     $this->post = $post;
  }
  public function __call($name, $arguments) {
    if(!method_exists($this, $name)) {
      die("Unknown action!");
    }
  }
  public function whatever() {
    echo json_encode($this->post['page_id']);
  }
  public function data() {
    echo '{"s":"OK"}';
  }
  // new action? just add another method
}

$controller = new Controller();
$controller->{$_POST('a')}(); // example 1
$controller->data(); // you can't do it using switch
  1. 易于添加新方法
  2. 易于维护
  3. 你可以随时激发你的方法
  4. 代码整洁
  5. 这真的很常见