开发者

Best practices to handle JSON data for API SDK

开发者 https://www.devze.com 2023-02-25 01:51 出处:网络
The company I work for has an API and I am porting that API over to PHP. Right now, the API returns to me a large JSON object and I\'m trying to figure out how I should handle the data.I could have a

The company I work for has an API and I am porting that API over to PHP. Right now, the API returns to me a large JSON object and I'm trying to figure out how I should handle the data. I could have a whole bunch of "get" methods, like:

$t = new APIThing();
$t->getJSONObjects();
for ($i=0; ...) {
   $t->getHeadline($i);
}

Or, I could return the JSON object and let people play with the data themselves, so that would be something like this

$t = new APIThing();
$t->getJSONObjects();
foreach ($t as $u) {
    echo $u->headline;
}

So what do 开发者_Python百科you think? Just expose the JSON object or wrap the whole thing up into functions?


instead of that you can have a class that gets anything from the JSON

class GETAPI {

   protected $api;

   function __construct(){
        $this->api = new APIThing();
        $this->api->getJSONObjects();
   }

   function getAllFromAPI($name){
       foreach($this->api as $u){
           echo $u->$name;
       }
   }

   //or :
   function getFromAPI($name, $index){
       return $this->api[$index]->$name;
   }

}

its rudimentary and could use some work, but that work over making many many get functions

than all you would have to do is something like:

$api = new GETAPI();

$api->getAllFromAPI('headline');
//or
echo $api->getFromAPI('headline', 1); // with one as the array index
0

精彩评论

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