所以我在
php.net左右徘徊,了解有关将PHP对象序列化为JSON的信息,当我偶然发现新的
JsonSerializable Interface时。它只有PHP> = 5.4,我在5.3.x环境中运行。
这种功能如何实现PHP, 5.4?
我没有使用JSON,但是我试图支持一个API层的应用程序,并将数据对象(否则将发送到视图)转储到JSON是完美的。
如果我试图直接序列化对象,它返回一个空的JSON字符串;这是因为我认为json_encode()不知道对对象做什么。我应该递归地减少对象到数组,然后编码吗?
例
$data = new Mf_Data();
$data->foo->bar['hello'] = 'world';
echo json_encode($ data)产生一个空对象:
{}
var_dump($ data)然而,按预期工作:
object(Mf_Data)#1 (5) {
["_values":"Mf_Data":private]=>
array(0) {
}
["_children":"Mf_Data":private]=>
array(1) {
[0]=>
array(1) {
["foo"]=>
object(Mf_Data)#2 (5) {
["_values":"Mf_Data":private]=>
array(0) {
}
["_children":"Mf_Data":private]=>
array(1) {
[0]=>
array(1) {
["bar"]=>
object(Mf_Data)#3 (5) {
["_values":"Mf_Data":private]=>
array(1) {
[0]=>
array(1) {
["hello"]=>
string(5) "world"
}
}
["_children":"Mf_Data":private]=>
array(0) {
}
["_parent":"Mf_Data":private]=>
*RECURSION*
["_key":"Mf_Data":private]=>
string(3) "bar"
["_index":"Mf_Data":private]=>
int(0)
}
}
}
["_parent":"Mf_Data":private]=>
*RECURSION*
["_key":"Mf_Data":private]=>
string(3) "foo"
["_index":"Mf_Data":private]=>
int(0)
}
}
}
["_parent":"Mf_Data":private]=>
NULL
["_key":"Mf_Data":private]=>
NULL
["_index":"Mf_Data":private]=>
int(0)
}
附录
1)
所以这是我为Mf_Data类设计的toArray()函数:
public function toArray()
{
$array = (array) $this;
array_walk_recursive($array, function (&$property) {
if ($property instanceof Mf_Data) {
$property = $property->toArray();
}
});
return $array;
}
然而,由于Mf_Data对象也有对它们的父(包含)对象的引用,因此递归失败。工作像一个魅力,虽然当我删除_parent引用。
2)
只是为了跟进,最终的功能来转换一个复杂的树节点对象我去与:
// class name - Mf_Data
// exlcuded properties - $_parent, $_index
public function toArray()
{
$array = get_object_vars($this);
unset($array['_parent'], $array['_index']);
array_walk_recursive($array, function (&$property) {
if (is_object($property) && method_exists($property, 'toArray')) {
$property = $property->toArray();
}
});
return $array;
}
3)
我再次跟进,有一点干净的实施。使用接口的instanceof检查看起来比method_exists()更清洁(然而method_exists()交叉切割继承/实现)。
使用unset()似乎有点凌乱,似乎逻辑应该重构到另一个方法。然而,这个实现复制属性数组(由于array_diff_key),所以需要考虑。
interface ToMapInterface
{
function toMap();
function getToMapProperties();
}
class Node implements ToMapInterface
{
private $index;
private $parent;
private $values = array();
public function toMap()
{
$array = $this->getToMapProperties();
array_walk_recursive($array, function (&$value) {
if ($value instanceof ToMapInterface) {
$value = $value->toMap();
}
});
return $array;
}
public function getToMapProperties()
{
return array_diff_key(get_object_vars($this), array_flip(array(
'index', 'parent'
)));
}
}