« Huge success I just discovered something amazing »

SilverStripe & PHP5.4 talk

Posted by Simon Welsh | 24 August 2011 | Comments (3)

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();
	}
}

Share on FaceBook

Trackbacks

None
Trackback URL: http://simon.geek.nz/Trackbacks/add/1345

Post your comment

Sign in with Twitter

Comments

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

    Posted by Simon Welsh, 16/11/2011 9:55pm (3 months ago)

  • I think the method looks and works great :D but have heard that json seems to be faster for encoding but slow in decoding.

    Posted by Justin Schneider, 16/11/2011 9:49pm (3 months ago)

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

    Posted by Bredd, 16/11/2011 9:19pm (3 months ago)

RSS feed for comments on this page | RSS feed for all comments