沒有辦法,即開即用,告訴教義將對象視爲一個數組。但是,通過一些調整和一些可疑的設計決定,您可以實現這一目標。
您需要做的第一件事就是創建一個實現ArrayAccess接口的基類(用於擴展類)。描述這個的文章可以在Doctrine cookbook找到。它會是這個樣子:
abstract class DomainObject implements ArrayAccess
{
public function offsetExists($offset)
{
return isset($this->$offset);
}
public function offsetSet($offset, $value)
{
throw new BadMethodCallException(
"Array access of class " . get_class($this) . " is read-only!"
);
}
public function offsetGet($offset)
{
return $this->$offset;
}
public function offsetUnset($offset)
{
throw new BadMethodCallException(
"Array access of class " . get_class($this) . " is read-only!"
);
}
}
然後,當你創建模型類(或至少要當作陣列的),你需要擴展這個domainObject的類。最後一塊難題是讓您的類屬性爲公開,以使json_encode函數能夠檢查您的類屬性並將它們用作json對象的鍵。
NB:在類中使用公有屬性會導致很多難以跟蹤的bug,並且通常被認爲是可疑的實踐。這只是一個例子,我很快就匆忙說明了如何實現。我相信有一種更優雅的方式來實現這一點,不需要公共屬性。該解決方案只是爲了讓球滾動
一個例子域類可能是這個樣子:
class Tester extends DomainObject
{
public $foo;
public $bar;
public function __construct($foo, $bar)
{
$this->foo = $foo;
$this->bar = $bar;
}
}
現在你就可以投出測試類的實例,以一個數組,並通該數組json_encode:
$test = new Tester('Hello', 'World');
echo json_encode((array)$test);
這將產生以下輸出:
{"foo":"Hello","bar":"World"}
編輯:只是爲了將您的代碼片段帶回到上下文中。你並不需要使用HYDRATE_ARRAY了,它只是看起來像這樣:
$results = $em->getRepository('MyBundle:Report')->findByEvaluation($evaluation_id);
foreach ($results as $result) {
echo json_encode((array)$result);
}
提供您的報告類擴展上述定義的domainObject的類。
感謝您的幫助,但正如您所指出的,它不是暴露實體屬性的最佳解決方案,所以我採用了我在下面發佈的解決方案。 – Sofia