A good way to send complex objects with ajax? - php

In my web app, I have some complex objects written with JavaScript (ie nested arrays, objects within objects withing objects, etc) and the nature of my app relies on these. I need to send all the data to PHP so that I can save it to the database. What is an efficient, easy way to send my objects to PHP? I tried JSON, but got strange errors like 'too much recursion', which I'm guessing means that my objects are too complex for it. So is there a good library of script that will do this? Thanks in advance.
EDIT:
So JSON then. I tried updating the JSON library to no avail, and I am now looking for cyclic references.

JSON is the right answer.
I suspect your JSON libraries are either broken or too restrictive. Check the JSON to see if it's well-formed, and if so, find a better library that can cope with your data structure.
Consider also simplifying the data structure. It may be too complex for your own good.

Pretty much any JSON library will have a too much recursion error if your object has circular references. The recursion limit of the javascript implementations I've tried is well in excess of ~100 levels deep, so your object would have to be really complicated.
You'll want to detect and eliminate circular references before trying to serialise your object using any sort of library.
edit: Just tested the firefox 3.5 and it tops out at 3000 levels of recursion.

I agree- JSON is the answer. I think the error you are encountering may be part of the library you are using...
http://markmail.org/message/2d5lvmdeg2qg55qr
Mentions the same error.
I've used many complex JSON objects and never encountered that error - I'd say something else is at play.

Related

What is more efficient to use Json_encode the data or to serialize the data and store in database?

Just came across serialize() in php. Many databases store the data in serialized form so curious to know what is more usefun json or serialize and why?
Json Data->["Math","Language","Science","History"]
serialized Data->a:4:{i:0;s:4:"Math";i:1;s:8:"Language";i:2;s:7:"Science";i:3;s:7:"History";}
Serialize() is a native PHP method of storing data in text strings. It can even store objects. And it has a special notation for objects. JSON, it its turn, is a JavaScript's Object Notation. Basically, same thing. But they are used in different domains.
JSON is usually used for online communication - sending data to/from AJAX scripts, numerous API's, etc. It appeared to be much lighter and readable than XML, thus it competes with it for the most commonly used data transfer standard for APIs. It is also widely used in config files, say, for Composter - where readability is one of the top requirements.
Visual readability and easy structure makes JSON the best way to communicate between different platforms and programming languages. This, last phrase is important.
PHP Serializing is used in cases where you save data in PHP and you restore data back in PHP as well. Say, you can save arrays, or $user object into a PHP session, and then restore them back. Or store a multi-dimensional array in a MySQL field, and then restore it exactly as it was in an $array variable. In most cases Serialized data is not much shorter/lighter than JSON and doesn't usually take less space - it makes it lose readability though. But there are quite powerful tricks with it PHP has - it preserves data types, classes names, visibility options, etc. Also refer to __sleep() and __wakeup() magic class methods allowing you to save objects on the fly and create special constructors to revive them back, again, on the fly.
In your particular case, if you store data in MySQL database with PHP, and then read it back to PHP - then PHP serialization would be the best way to use. Unless you want to access this data with other languages, or edit manually/visually.
to complete Oleg's answer I would like to suggest you to visit this link with objetive comparisons between json_encode and serialize PHP methods:
http://www.shozab.com/php-serialization-vs-json-encoding-for-an-array
It shows how serialize is usually slower but not recommended for all situations.
And finally here you have another discussion with many contributions in stackoverflow:
Serialize or json in PHP?
Hope it will be interesting for you.

php - array or objects to store data - what is better solution

I am just thinking what would give me better perfomance and memory usage. I am programming a map for a game. Everything is stored in class "map" but a map may have thousands of tiles. Now i am thinking what is better solution:
keep every tile parameters in x-y array (tile x = 10, y = 11 data is stored in array like map[10][11] = params) and if i want to know something about a tile a call different arrays with x-y parameters
consider a tile as an object and make methods to, it can easily return tile's neighbours and all data also stored somehere in each object as an array.
Because I may have thousands of similiar tiles first impression would be that it is best for oop programming, but i am afraid that thousands of object tiles might use much more memory and calling to it's methods might be slower. What do you think about it?
Kalreg
It depends on the php version you are using. If the version you are using is PHP5 or above(which you should as latest php version will mean more performance for your game app) then using both arrays and objects will give almost same performance for your application. So if you are-using/can-use PHP 5 or above then you may use arrays or objects according to your convenience.
Check this array vs object comparison/tests by Aron Novak: http://aggregation.novaak.net/?q=node/227.
I am quoting it bellow in Aron Novaks words:
I created a small script to find out which data structure has better performance. You can find the script what I used for the test at the attachments.
My test results are:
data structure PHP4 PHP5
object 61.6224 37.576
array 57.6644 37.866
The results are in milliseconds(ms). It seems that in PHP5 the data structure is totally indifferent, in PHP4 there is approximately 7% performance gain if use arrays instead of objects.
"This revolution, however, left PHP's object model mostly unchanged from version 3 – it was still very simple. Objects were still very much syntactic sugar for associative arrays, and didn't offer users too many features on top of that." (http://devzone.zend.com/node/view/id/1717)
So the syntactic sugar is not a bad thing at all :) And it costs almost nothing. This is an explanation why all the parsers' output uses objects.
Check this http://we-love-php.blogspot.com/2012/06/php-memory-consumption-with-arrays.html for a detailed/great article on PHP arrays vs objects memory Usage and Performance
You are developing a game definitely you can not use only array or objects you are mostly likely to use both.
I think you should first understand How big are PHP arrays (and values) really? (Hint: BIG!)
Replace your array with SplFixedArray and store your objects in SplObjectStorage you should get improvements in your code.
If you have a grid of tiles, that lends itself really well to being stored in an array.
But if those tiles have a lot of information attached to them, that lends itself to objects.
I would suggest an array of objects.

Mapper between json and php class

I'm starting a new project that uses couchbase (a noSQL database that stores objects in json format), together with php.
The thing is that it would be really easy to work with them both if I could have something that maps json into one of my own php classes (and vice versa).
Do you know any library for that?
One way to start is to look (or use) the "Basement" Library that is available here:
https://github.com/Basement/Basement
This library uses json_decode/encode.
Hope that will help you.
You may use our JSONmapper to map from JSON to your PHP classes.
It unfortunately does not support mapping back (yet).
Tug already mentioned Basement, which will provide that functionality of "models" in the near future like you know it from ORM systems.
Aside from that, mapping your plain old php objects to JSON is very easy, thanks to the nature of json_encode/decode. Since you can pass it an arbitary object and it will store it as JSON, thats basically the only thing you need at hand. If you need more infos about JSON and PHP, my blog post is a good start: http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP
If you use Basement, it makes it a little bit easier for you since it allows you to transform PHP types into JSON behind the scenes automatically (or write your own mapper if needed).
If you have a specific example that you want to build, let me know and I'd be happy to provide an example!

Zend AMF Optimisation; Tips and Tricks?

I am working on a project that uses PHP to create an 'complex' object with lots of references to other objects linking back to their parent objects etc...
The object structure is then serialized by the Zend AMF module and sent over to the flex application.
The problem is that serialization takes a lot of time (+10sec).
My question is thus: can anybody give me tips on how the serialization works and in what way I may be able to optimize the object structure in order to make serialization run faster?
Switching to JSON will help a great deal with this, as it allows easier caching.
APC will also help, just for the opcode-cache part, not for storing objects in memory.
How big is this object exactly? Could it be worth it not sending the entire thing? If you're just dealing with recordsets, you might be able to fix it in the frontend by only downloading only what the user can see, or will see in the near future.
The default serializer will iterate through every property, if a property is an object it will then iterate through each of those objects and their properties until it's done.
Since your object is complex, there's lots of crunching going on and many levels of objects that are being serialized.
As a point of optimization you may wish to look into implementing the serializable interface on your objects and serializing the minimal amount of information you require to be serialized and sent over the wire to your Flex app.
http://php.net/manual/en/class.serializable.php
When doing AMF serialization, or any serialization for that matter, it is usually better to work with smaller pieces of data if performance is a concern. By doing that you can work with individual objects as true ActionScript objects instead of just data placeholders. Smaller data when doing any type of RPC is usually better. You could use JSON instead, but then you'd loose the tight data binding that you get from using AMF. So try working with smaller packets of data using multiple HTTP requests.

Should I go for Arrays or Objects in PHP in a CouchDB/Ajax app?

I find myself converting between array and object all the time in PHP application that uses couchDB and Ajax. Of course I am also converting objects to JSON and back (for sometimes couchdb but mostly Ajax), but this is not so much disturbing my workflow.
At the present I have php objects that are returned by the CouchDB modules I use and on the other hand I have the old habbit to return arrays like array("error"=>"not found","data"=>$dataObj) from my functions. This leads to a mixed occurence of real php objects and nested arrays and I cast with (object) or (array) if necessary. The worst thing is that I know more or less by heart what a function returns, but not what type (array or object), so I often run into type errors.
My plan is now to always cast arrays to objects before returning from a function. Of course this implies a lot of refactoring.
Is this the right way to go? What about the conversion overhead? Other ideas or tips?
Edit: Kenaniah's answer suggests I should go the other way, this would mean I'd cast everything to arrays. And for all the Ajax / JSON stuff and also for CouchDB I would use
$myarray = json_decode($json_data,$assoc = true); //EDIT: changed to true, whcih is what I really meant
Even more work to change all the CouchDB and Ajax functions but in the end I have better code.
Generally speaking, you should always use arrays unless there is a good reason to use objects. And the only good reason to use objects over arrays in PHP is if you need some sort of functionality for your data that arrays do not provide (such as private / protected variables, methods, object magic, defined structure, etc). If you're dealing strictly with data, array format is better because you can easily manipulate your data using PHP's vast array of array functions (no pun intended).
UPDATE:
If all you are doing is passing data between two points, arrays are much more suited for that purpose. The only reason (as far as I can tell) that one would ever use an object over an array as a mere container for data is if the receiving side needed a guaranteed format (think interfaces, etc).
From what I can tell, you should be returning arrays from CouchDB to avoid having to convert altogether.
It depends on the paradigm you want to work in. Fundamentally your data is all key-value pairs stored in CouchDB. Maybe it can be easily mapped to objects/entities and you are more comfortable thinking of it in terms of objects that have properties and methods. Or, maybe not and maybe you are more comfortable working with the raw data without the abstraction that classes provide. I think this is the key distinction that should inform your decision.
There is not a lot of overhead involved with objects vs. arrays in PHP. Internally they are treated similarly by the PHP engine. You might want to benchmark it yourself if it's a concern, but I think that you won't find a lot of difference unless you are pushing massive traffic or have a very constrained server. Obviously your web app would be faster if you wrote it in optimized x86 assembler, but you don't do that because you want to be able to enjoy the convenience that a high-level language like PHP provides. So execute the best design now, and optimize later, if it's even necessary.

Categories