开发者

Should I create wrappers for all my RESTful JSON exchanges?

I have multiple calls to many RESTful services. I translate to PHP using native PHP json_decode when I receive the data, and use json_encode when sending data.

My concern is that with deeply nested data I end up writing code like:

$interestType = $person['children'][$i]['interests'][$j]['type'];

This can get quite messy. I feel there would be some benefit in creati开发者_如何转开发ng objects whose methods/instance variables wrap around these structures, such that I could do:

$interestType = $person->getChild($i)->getInterest($j)->getType();

It seems clearer to me, but in reality it's not much more concise.

What are the benefits of just doing everything using native PHP arrays, and writing wrapper classes for each REST resource?

My concern is that I will have to write custom encode/decode functions to map to these wrappers.


I am not familiar with the implementation of objects in PHP, but reading this blogpost about array vs object performance, it seems the overhead is minimal. So I guess it boils down to style preferences. A simple (not-nested) array to object converter can be found here:

  • http://www.lost-in-code.com/programming/php-code/php-array-to-object/

A compromise, which would be trivial to implement:

<?php

$json = '{"a": [{"aa" : 11}, {"ab" : 12}],"b":2,"c":3,"d":4,"e":5}';

$o = json_decode($json);       // plain object
$a = json_decode($json, true); // this will yield an array

echo $o->a[0]->aa;

?>

json_decode takes an optional argument, that determines, if the supplied JSON is converted to an associative array. If it isn't ($o), you have half the syntax, you aim for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜