Scared of the Peacock Revolution since 2006
Blog » SilverStripe & PHP5.4 talk
I gave a talk tonight at the SilverStripe meetup on SilverStripe and PHP5.4. A PDF copy of my slides is available here.
My custom Convert::raw2json() method to have JsonSerializable support in PHP 5.3
static function raw2json($val) {
if(version_compare(PHP_VERSION, '5.4') < 0) {
$val = self::raw2jsonSerialize($val);
}
if(function_exists('json_encode')) {
return json_encode($val, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP|JSON_PRETTY_PRINT);
} else {
require_once(Director::baseFolder() . '/sapphire/thirdparty/json/JSON.php');
$json = new Services_JSON();
return $json->encode($val);
}
}
protected static function raw2jsonSerialize($val) {
if(is_array($val)) {
foreach($val as &$var) {
$var = self::raw2jsonSerialize($var);
}
} elseif(is_object($val) && $val instanceof JsonSerializable) {
$val = $val->jsonSerialize();
if(is_array($val)) {
$val = self::raw2jsonSerialize($val);
}
}
return $val;
}
The interface file that declares JsonSerializable, if needed:
<?php
if(!interface_exists('JsonSerializable')) {
interface JsonSerializable {
public function jsonSerialize();
}
}
I only use JSON when giving data to a browser and, as JSON is pure javascript, it gets all the advantages of the speedups in the current javascript engines.
For server->server, I still prefer XML.
I think the method looks and works great :D but have heard that json seems to be faster for encoding but slow in decoding.
I couldn't compile SilverStripe and PHP 5.4 and it's a sad thing, since websites with SilverStripe are really easy to edit because it provides an intuitive to use, powerful content management system.
RSS feed for comments on this page | RSS feed for all comments
And when he had fasted forty days and forty nights, he was afterward an hungered.
Powered by SilverStripe. Hosted by RimuHosting.
Unlease otherwise stated, all content is licenced under a Creative Commons Attribution-ShareAlike Licence.