PHP创建模型最佳实践

时间:2014-02-28 23:16:23

标签: php class models extends

我正在为我在 PHP 中构建的API创建一些模型类,以便为JSON响应提供严格的结构。这是一个例子:

class Model {
    public $id;

    public function __construct($id) {
        $this->id = $id;
    }
}

class ExecutionQueue extends Model {
    public $current_status;
    public $events;

    public function __construct($id, $current_status, array $events = array()) {
        parent::__construct($id);
        $this->current_status = $current_status;
        $this->events = $events;
    }
}

class Event {
    public $status;
    public $date;

    public function __construct($status, $date) {
        $this->status = $status;
        $this->date = $date;
    }
}

$execution_queue = new ExecutionQueue('id_sdjdfV4s33KffsTdaD43', 'QUEUED', array(
    new Event("QUEUED", "2014-02-28T20:59:08+0000"),
    new Event("RUNNING", "2014-02-28T20:59:08+0000"),
    new Event("COMPLETED", "2014-02-28T20:59:08+0000")
));

echo json_encode($execution_queue, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

这导致以下JSON响应:

{
    "current_status": "QUEUED",
    "events": [
        {
            "status": "QUEUED",
            "date": "2014-02-28T20:59:08+0000"
        },
        {
            "status": "RUNNING",
            "date": "2014-02-28T20:59:08+0000"
        },
        {
            "status": "COMPLETED",
            "date": "2014-02-28T20:59:08+0000"
        }
    ],
    "id": "id_sdjdfV4s33KffsTdaD43"

}

我有几个问题。首先,是否可以让id在JSON响应中返回高于 current_statusevents?其次,如何在Event下嵌套ExecutionQueue类,这样我就不会污染全局类名空间,即如果我想在不同的模型下创建另一个Event类?最后,任何可以改进和清理并使其更加面向对象的东西?

0 个答案:

没有答案