Should I create wrappers for all my RESTful JSON exchanges? - php

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 creating 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.

Related

What kind of object is this?

I'm trying to load this object in python or PHP, but I'm now trying to know if there are libraries that are already written so that I don't parse the document myself.
variable = [["1","arbitrary string","another arbitrary string"],
["2","arbitrary string","another arbitrary string"],
["3","arbitrary string","another arbitrary string"],
["4","arbitrary string","another arbitrary string"]];
another_variable = "arbitrary string";
Any hints will be appreciated.
Thanks
This looks a lot like JSON. PHP has some built-in functions to handle it - json_decode, for instance: http://www.php.net/manual/en/function.json-decode.php.
It looks like Python also has a JSON library built-in: http://docs.python.org/3/library/json.html (the same library is available in Python 2 as well, if you're still using the "older" version).
That is a JSON encoded string, representing an array of arrays.
You can make it a PHP native element using :
$var = json_decode($variable);
Do note that json_decode() is build-in to PHP after 5.2 only. Otherwise you'll have to get it from PEAR.

PHP: is this a bug: shuffle() expects parameter 1 to be array, object given?

I have an object that implements the ArrayableInterface (BTW, it's from Laravel's Eloquent ORM).
This object is $articles. So naturally, I can do this:
foreach ($articles as $article)
echo $article->title . "<br/>";
But I can't do this:
shuffle($articles);
I get the shuffle() expects parameter 1 to be array, object given warning.
No, it's not a bug.
PHP 5 allows you to use foreach() to loop through objects that aren't arrays. These objects are called Iterators.
Unfortunately, the old array-based functions, like shuffle() cannot process Iterators.
The main reason for this is that an Iterator may not even be sortable -- for example, you can have iterators that read directly from a file or a URL, and read a new line of data each time the foreach() loop cycles. This clearly can't be sorted because it's read during the foreach() process.
You can convert an Iterator into an array, using the cleverly named iterator_to_array() function. However, this may be a bad idea if you don't know how much data the iterator is going to process, as you may find it uses a lot of memory.
Some iterators may provide methods within the iterator object itself for sorting or filtering the data. If so, this is a better solution than trying to sort it as an array.
If you're working with an ORM, then this implies that your Iterator object is reading data from a DB. In this case, sorting it via the DB query (ie ORDER BY or whatever methods the ORM provides to do that) would probably be a better solution than sorting the data in PHP.
I don't know what the interface does.. but nor will the shuffle function because it only recognises arrays. You'd need to do this:
$array = iterator_to_array($articles);
$shuffled = shuffle($array);
From an OOP perspective, really, your object should contain the shuffle implementation:
$articles->shuffle();

PHP mysql code help decoding

I have this value under Items in my DB:
a:1:{i:0;a:9:{s:12:"model_number";s:10:"TT1-W";s:5:"price";s:4:"3810";s:10:"unit_price";d:3135.6300000000001091393642127513885498046875;s:8:"id_price";d:3810;s:9:"sales_tax";d:290.3700000000000045474735088646411895751953125;s:5:"sales";d:3084.6300000000001091393642127513885498046875;s:7:"service";s:2:"51";s:7:"freight";s:3:"384";s:13:"co_cat";s:3:"X4";}}
Making it more reader-friendly:
a:1:
{
i:0;
a:9:
{
s:12:"model_number";
s:10:"TT1-W";
s:5:"price";
s:4:"3810";
s:10:"unit_price";
d:3135.6300000000001091393642127513885498046875;
s:8:"id_price";
d:3810;
s:9:"sales_tax";
d:290.3700000000000045474735088646411895751953125;
s:5:"sales";
d:3084.6300000000001091393642127513885498046875;
s:7:"service";
s:2:"51";
s:7:"freight";
s:3:"384";
s:13:"co_cat";
s:3:"X4";
}
}
I am unable to find out how to decode this string since it can not seem to find reference to it in the php code that displays it on the page. It looks to me to be JSON but i can not seem to find a "standard" format for the above in order to start figuring out where it starts and where it ends.
I am needing this to be decoding using ASP.net. But then again, i need to figure out what it is before i can start decoding it!
Any help to what it is would be great!
Try with unserialize:
function.unserialize
EDIT: If you can use C# libraries:
How to unserialize PHP Serialized array/variable/class and return suitable object in C#
EDIT2:
Visual Studio Tip: Three ways to use C# within a VB.NET project
EDIT3:
i need to figure out what it is
It's standard PHP-solution to store (and restore) arrays and objects (and other types, see manual) in strings.
That appears to be PHP's serialization methodology. You just need to use PHP's unserialize() on it.
This looks a serialized object. PHP's unserialize is probably what you want:
unserialize() takes a single serialized variable and converts it back
into a PHP value.
There is no built in way to turn that into an ASP.Net object, but it is a regular format, so you can build your own parser to create a simple dictionary representation of the attributes of that particular structure.
But if you're trying to de-serialize a PHP object in ASP.Net you're probably doing something wrong!

XML or JSON reponse for Flex applications with PHP backend?

I'm developing a floorplanner Flex mini application. I was just wondering whether JSON or XML would be a better choice in terms of performance when generating responses from PHP. I'm currently leaning for JSON since the responses could also be reused for Javascript. I've read elsewhere that JSON takes longer to parse than XML, is that true? What about flexibility for handling data with XML vs JSON in Flex?
I'd go with JSON. We've added native JSON support to Flash Player, so it will be as fast on the parsing side as XML and it's much less verbose/smaller.
=Ryan ryan#adobe.com
JSON is not a native structure to Flex (strange, huh? You'd think that the {} objects could be easily serialized, but not really), XML is. This means that XML is done behind the scenes by the virtual machine while the JSON Strings are parsed and turned into objects through String manipulation (even if you're using AS3CoreLib)... gross... Personally, I've also seen inconsistencies in JSONEncoder (at one point Arrays were just numerically indexed objects).
Once the data has been translated into an AS3 object, it is still faster to search and parse data in XML than it is with Objects. XPath expressions make data traversal a pleasure (almost easy enough to make you smile compared to other things out there).
On the other hand JS is much better at parsing JSON. MUCH, MUCH BETTER. But, since the move to JavaScript is a "maybe... someday..." then you may want to consider, "will future use of JSON be worth the performance hit right now?"
But here is a question, why not simply have two outputs? Since both JS and AS can provide you POSTs with a virtually arbitrary number of variables, you really only need to concern yourself with how the server send the data not receives it. Here's a potential way to handle this:
// as you are about to output:
$type = './outputs/' . $_GET[ 'type' ] . '.php';
if( file_exists( $type ) && strpos( $type, '.', 1 ) === FALSE )
{
include( $type );
echo output_data( $data );
}
else
{
// add a 404 if you like
die();
}
Then, when getting a $_GET['type'] == 'js', js.php would be:
function output_data( $data ){ return json_encode( $data ); }
When getting $_GET['type'] == 'xml', xml.php would hold something which had output_data return a string which represented XML (plenty of examples here)
Of course, if you're using a framework, then you could just do something like this with a view instead (my suggestion boils down to "you should have two different views and use MVC").
No, JSON is ALWAYS smaller than XML when their structures are completely same. And the cost of parsing text is almost up to the size of the target text.
So, JSON is faster than XML and if you have a plan to reuse them on javascript side, choose JSON.
Benchmark JSON vs XML:
http://www.navioo.com/ajax/ajax_json_xml_Benchmarking.php
If you're ever going to use Javascript with it, definitely go with JSON. Both have a very nice structure.
It depends on how well Flex can parse JSON though, so I would look into that. How much data are you going to be passing back? Error/Success messages? User Profiles? What kind of data is this going to contain?
Is it going to need attributes on the tags? Or just a "structure". If it needs attributes and things like that, and you don't want to go too deep into an "array like" structure, go with XML.
If you're just going to have key => value, even multi-dimensional... go with JSON.
All depends on what kind of data you're going to be passing back and forth. That will make your decision for you :)
Download time:
JSON is faster.
Javascript Parse
JSON is faster
Actionscript Parse
XML is faster.
Advanced use within Actionscript
XML is better with all the E4X functionality.
JSON is limited with no knowledge of Vectors meaning you are limited to Arrays or will need to override the JSON Encoder in ascorelib with something such as
else if ( value is Vector.<*> ) {
// converts the vector to an array and
return arrayToString( vectorToArray( value ) );
} else if ( value is Object && value != null ) {
private function vectorToArray(__vector:Object):Array {
var __return : Array;
var __vList : Vector.<*>;
__return = new Array;
if ( !__vector || !(__vector is Vector.<*>) )
{
return __return;
}
for each ( var __obj:* in (__vector as Vector.<*>) )
{
__return.push(__obj);
}
return __return;
}
But I am afraid getting those values back into Vectors is not as nice. I had to make a whole utility class devoted to it.
So which one is all depending on how advanced your objects you are going to be moving.. More advanced, go with XML to make it easier ActionScript side.
Simple stuff go JSON

How-to Serialize/Unserialize a SimpleXML Object?

I've seen a few creative solutions for dealing with serialized SPL objects but am looking for more options (or elaborations). I store nested serialized objects - of which, one is SimpleXML - in the database, only to be un-serialized later. This obviously cause some problems.
$s = new SimpleXmlElement('<foo>bar</foo>');
$ss = serialize($s);
$su = unserialize($ss);
// Warning: unserialize() [function.unserialize]: Node no longer exists...
Does anyone have any insight into highly-reliable methods for dealing with serialized SPL objects? __sleep()/__wakeup() overrides? Cast-to-stdClass? Cast-to-string, then serialize?
Any help is appreciated.
[Edit: The scope and variation of these XML schemas are too varied to map with an ORM. They are, at their most fundamental level, arbitrary payloads in stateful processes, triggered within restful APIs.]
Questions on appropriateness notwithstanding, you can turn it back into XML like this:
$xml = $simpleXmlElem->asXML();
And then, when you pull it from the database:
$simpleXmlElem = simplexml_load_string($xml);
As for whether it's appropriate to just serialize large chunks of XML, it can be true that putting XML into the database removes much of the advantage of using a relational system, but you do have the advantage of being able to accommodate an arbitrary workload. If some fields are universal, and/or you gain benefit from normalizing them properly (e.g. you want to select based on those fields), move those into normalized columns.
More clear and OOP.
namespace MyApp;
class SimpleXMLElement extends \SimpleXMLElement
{
public function arrayToXml($array = array())
{
array_walk_recursive($array, array(&$this, 'addChildInverted'));
return $this;
}
public function addChildInverted($name ,$value)
{
parent::addChild($value,$name);
}
}
and calling
$xml = new \MyApp\SimpleXMLElement('<resultado/>');
echo $xml->arrayToXml($app->getReturnedValue())->asXML();
Wouldn't simply rendering and storing the XML be the best way to serialize any object that represents an XML structure?
What are you trying to do with the serialized data that might prevent this?
edit:
Also,
I store nested serialized objects [...] in the database, only to be un-serialized later
Why are you storing PHP serialized data in a database? There are many better ways to store objects in a database.

Categories