<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Squio.blog &#187; Java</title>
	<atom:link href="http://squio.nl/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://squio.nl</link>
	<description>Creative internet development</description>
	<lastBuildDate>Thu, 03 Jun 2010 07:35:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>PHP, Reflection and JSON: stream your objects</title>
		<link>http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/</link>
		<comments>http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/#comments</comments>
		<pubDate>Tue, 17 Oct 2006 21:18:29 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[webdev]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON stream]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/</guid>
		<description><![CDATA[Amongst all the improvements in PHP 5 is the concept of Reflection. If you&#8217;re a Java person, you will be familiar with this concept. In just a few words, Reflection means that Objects are open to (self-) inspection, so that you can interrogate an object for all kinds of properties at runtime. Now if you [...]]]></description>
			<content:encoded><![CDATA[<p>Amongst all the improvements in PHP 5 is the concept of <a href="http://www.php.net/language.oop5.reflection">Reflection</a>. If you&#8217;re a Java person, you will be familiar with this concept.</p>
<p>In just a few words, Reflection means that Objects are open to (self-) inspection, so that you can interrogate an object for all kinds of properties at runtime.</p>
<p>Now if you have classes with getter (and setter) methods, there are some very elegant techniques with reflection. Normally, these getters and setters are used to give access to the data contained in the object. Good Object Oriented practice makes use of these <a href="http://en.wikipedia.org/wiki/Data_object">Data Objects</a> to build a clean boundary between the data and implementation details.</p>
<p>So, let&#8217;s assume that you have painfully crafted a class definition with accessors and you want to serialize the contained data as <a href="http://json.org/">JSON</a> over the wire. Of course, you can write a <em>getJsonString()</em> method for every class. But Reflection gives you a much nicer option.</p>
<p>An example of serialization into JSON, entirely based on Reflection:<br />
<span id="more-45"></span></p>
<pre>
function toDataObj($myObj) {
    $ref = new ReflectionClass($myObj);
    $data = array();
    foreach (array_values($ref-&gt;getMethods()) as $method) {
        if ((0 === strpos($method-&gt;name, "get"))
                &#038;&#038; $method-&gt;isPublic()) {
            $name = substr($method-&gt;name, 3);
            $name[0] = strtolower($name[0]);
            $value = $method-&gt;invoke($myObj);
            if ("object" === gettype($value)) {
                $value = toDataObj($value);
            }
            $data[$name] = $value;
        }
    }
    return $data;
}

print json_encode(toDataObj($myObj));
</pre>
<p><strong>What is going on here?</strong><br />
First, I have a <em>data object</em>, referenced by <em>$myObj</em>, with a couple of getter methods.<br />
Then, a new reflection object is instantiated for <em>myObj.</em> This reflection object contains a whole lot of reflection methods, of which <em>getMethods()</em> is used here.<br />
In the <em>foreach</em> loop, a every method of the <em>myObj</em> is inspected in turn. Here we look for methods whose name start with &#8220;get&#8221; (the <em>name</em> property). Then we normalize the name (getMyVariable => myVariable) and call the original method of <em>myObj</em> through <em>invoke($myObj)</em>.<br />
If the returned value is an object itself, the function <em>toDataObj</em> is recursively called with this object.<br />
Then, the name, value pair is stored in a hash list (called Array in PHP).<br />
Finally, this hash is serialized into JSON.</p>
<p>The cool thing is that this function is really universal.<br />
It will take just any object with getter methods and due-fully serialize the data, which then can be turned into a JSON stream, ready to consume in your Ajax applications.</p>
<p><strong>Reflection class</strong><br />
The Reflection class and all of its subclasses are available in PHP 5.1.x, no need to include anything.</p>
<p><strong>PHP JSON</strong><br />
If you&#8217;re running PHP 5.1.x, you most likely have <em>json_encode()</em> available, but you may need to enable the <a href="http://www.aurore.net/projects/php-json/">php_json</a> extension in php.ini.<br />
Otherwise <a href="http://www.aurore.net/projects/php-json/">download</a>, build and install the extension and add the line <em>extension=php_json.so</em> (*nix) or <em>extension=php_json.dll</em> (Win32) in php.ini and you should be up and running.</p>
<div class="tags"><a rel="tag" href="http://technorati.com/tag/php">php</a><a rel="tag" href="http://technorati.com/tag/reflection">reflection</a><a rel="tag" href="http://technorati.com/tag/json">json</a><a rel="tag" href="http://technorati.com/tag/oop">oop</a></div>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=PHP%2C+Reflection+and+JSON%3A+stream+your+objects+http://squio.nl/?p=45" title="Post to Twitter"><img class="nothumb" src="http://squio.nl/blog/wp-content/plugins/tweet-this/icons/tt-twitter3.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=PHP%2C+Reflection+and+JSON%3A+stream+your+objects+http://squio.nl/?p=45" title="Post to Twitter">Tweet This</a> <a class="tt" href="http://delicious.com/post?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to Delicious"><img class="nothumb" src="http://squio.nl/blog/wp-content/plugins/tweet-this/icons/tt-delicious.png" alt="Post to Delicious" /></a> <a class="tt" href="http://delicious.com/post?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to Delicious">Delicious</a> <a class="tt" href="http://reddit.com/submit?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to Reddit"><img class="nothumb" src="http://squio.nl/blog/wp-content/plugins/tweet-this/icons/tt-reddit.png" alt="Post to Reddit" /></a> <a class="tt" href="http://reddit.com/submit?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to Reddit">Reddit This Post</a> <a class="tt" href="http://stumbleupon.com/submit?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to StumbleUpon"><img class="nothumb" src="http://squio.nl/blog/wp-content/plugins/tweet-this/icons/tt-su.png" alt="Post to StumbleUpon" /></a> <a class="tt" href="http://stumbleupon.com/submit?url=http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/&amp;title=PHP%2C+Reflection+and+JSON%3A+stream+your+objects" title="Post to StumbleUpon">Stumble This Post</a></p><img src="http://squio.nl/blog/?ak_action=api_record_view&id=45&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://squio.nl/blog/2006/10/17/php-refection-and-json-stream-your-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
