API Design: Multiple $_REQUEST's vs single $_REQUEST encoded in json
I'm building an API, and I'm at a crossroads as how to implement it. I plan on using json, since they can represent objects/arrays so easily in php and javascript.
I have two ways to implement it pretty much:
1) Include the method call into the json
$input = $_REQUEST['i'];
$i_obj = json_decode($input);
api_handle($i_obj);
2) Push the method call (and perhaps other variables, such as the session) in parallel, and just pull the data via $_REQUEST.
$method = $_REQUEST['m'];
$argv = json_decode($_REQUEST['argv']);
api_handle($method,$argv);
I can see that in the second case, there may be less for the json_decode to debug, but from a user friendly point of view, an ajax/js coder could just build the object and send it json_encoded via input "i".
My question in the end is, are either of these good ways to implement this, or is there perhaps an even better way? P开发者_运维技巧lease keep in mind, this is a simple example, and does not represent the rest of the project's scope for this API.
In this particular case it's better idea to couple all method call data into one object rather then getting it from $_REQUEST
key by key since $_REQUEST
contains other unrelated data as well at the same level.
Method name and its arguments are tied together and must be transferred as single packet. Maybe some day you'll deside to add ability to call i.e. class static methods. It will be much harder to add one more key to $_REQUEST
and its processing then add one more field to object since object is much more encapsulated thing and that will narrow area affected by changes in your code.
And of course you can name object fields by a whim withot thinking if this key is already taken in $_REQUEST
by another script.
精彩评论