我正在为我在 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_status
和events
?其次,如何在Event
下嵌套ExecutionQueue
类,这样我就不会污染全局类名空间,即如果我想在不同的模型下创建另一个Event
类?最后,任何可以改进和清理并使其更加面向对象的东西?