<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Gonzalo Ayuso &#124; Web Architect</title>
	<atom:link href="https://gonzalo123.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://gonzalo123.wordpress.com</link>
	<description></description>
	<lastBuildDate>Sun, 22 Jan 2012 13:33:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gonzalo123.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/36e61d26ff749c3064487f5bc33ff092?s=96&#038;d=https%3A%2F%2Fs-ssl.wordpress.com%2Fi%2Fbuttonw-com.png</url>
		<title>Gonzalo Ayuso &#124; Web Architect</title>
		<link>https://gonzalo123.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://gonzalo123.wordpress.com/osd.xml" title="Gonzalo Ayuso &#124; Web Architect" />
	<atom:link rel='hub' href='https://gonzalo123.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Checking the performance of PHP exceptions</title>
		<link>https://gonzalo123.wordpress.com/2012/01/16/checking-the-performance-of-php-exceptions/</link>
		<comments>https://gonzalo123.wordpress.com/2012/01/16/checking-the-performance-of-php-exceptions/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 13:18:12 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[micro-optimizations]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[benchmark test]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[language php]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1196</guid>
		<description><![CDATA[Testing the performance using exceptions within our PHP scripts<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1196&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Sometimes we use exceptions to manage the flow of our scripts. I imagine that the use of exceptions must have a performance lack. Because of that I will perform a small benchmark to test the performance of one simple script throwing exceptions and without them. Let’s start:</p>
<p>First a silly script to find even numbers (please don&#8217;t use it it&#8217;s only for the benchmanrk <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )<br />
<pre class="brush: php;">
error_reporting(-1);
$time = microtime(TRUE);
$mem = memory_get_usage();

$even = $odd = array();
foreach (range(1, 100000) as $i) {
  try {
    if ($i % 2 == 0) {
      throw new Exception(&quot;even number&quot;);
    } else {
      $odd[] = $i;
    }
  } catch (Exception $e) {
    $even[] = $i;
  }
}
echo &quot;odds: &quot; . count($odd) . &quot;, evens &quot; . count($even);
print_r(array('memory' =&gt; (memory_get_usage() - $mem) / (1024 * 1024), 'microtime' =&gt; microtime(TRUE) - $time));
</pre></p>
<p>And now the same script without exceptions.</p>
<p><pre class="brush: php;">
error_reporting(-1);
$time = microtime(TRUE);
$mem = memory_get_usage();

$even = $odd = array();
foreach (range(1, 100000) as $i) {
    if ($i % 2 == 0) {
        $even[] = $i;
    } else {
        $odd[] = $i;
    }
}

echo &quot;odd: &quot; . count($odd) . &quot;, evens &quot; . count($even);
print_r(array('memory' =&gt; (memory_get_usage() - $mem) / (1024 * 1024), 'microtime' =&gt; microtime(TRUE) - $time));
</pre></p>
<p>The outcomes:<br />
<strong>with exceptions</strong><br />
<strong>memory</strong>: 10.420181274414<br />
<strong>microtime</strong>: 1.1479668617249</p>
<p><strong>without exceptions</strong><br />
<strong>memory</strong>: 10.418941497803<br />
<strong>microtime</strong>: 0.14752888679505</p>
<p>As we can see the use of memory is almost the same and ten times faster without exceptions.</p>
<p>I have done this test using a VM box with 512MB of memory and PHP 5.3.<br />
Now we are going to do the same test with a similar host. The same configuration but PHP 5.4 instead of 5.3</p>
<p><strong>PHP 5.4:</strong><br />
<strong>with exceptions</strong><br />
<strong>memory</strong>: 7.367259979248<br />
<strong>microtime</strong>: 0.1864490332</p>
<p><strong>without exceptions</strong><br />
<strong>memory</strong>: 7.3669052124023<br />
<strong>microtime</strong>: 0.089046955108643</p>
<p>I&#8217;m really impressed with the outcomes. The use of memory here with PHP 5.4 is much better now and the execution time better too (ten times faster).</p>
<p>According to the outcomes my conclusion is that the use of exceptions in the flow of our scripts is not as bad as I supposed. OK in this example the use of exceptions is not a good idea, but in another complex script exceptions are really useful. We also must take into account the tests are iterations over 100000 to maximize the differences. So I will keep on using exceptions. This kind of micro-optimization not seems to be really useful. What do you think?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1196/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1196/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1196&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2012/01/16/checking-the-performance-of-php-exceptions/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with clouds. Multi-master file-system replication with CouchDB</title>
		<link>https://gonzalo123.wordpress.com/2012/01/02/working-with-clouds-multi-master-file-system-replication-with-couchdb/</link>
		<comments>https://gonzalo123.wordpress.com/2012/01/02/working-with-clouds-multi-master-file-system-replication-with-couchdb/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 13:46:46 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[CouchDB]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1184</guid>
		<description><![CDATA[When we work with clouds we need to take care with the filesystem. In this post we will see a simple way to replicate our files between all nodes<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1184&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When we want to work with a cloud/cluster one of the most common problems is the file-system. It&#8217;s mandatory to be able to scale horizontally (scale out). We need to share the same file-system between our nodes. We can do it with a file server (<a href="http://en.wikipedia.org/wiki/Samba_(software)">samba </a>for example), but this solution inserts a huge bottleneck into our application. There&#8217;s different distributed filesystems such as Apache <a href="http://hadoop.apache.org/">Hadoop</a> (inspired by Google’s MapReduce and Google File System). In this post we’re going to build a really simple distributed storage system based on NoSql. Let’s start.</p>
<p>NoSql (aka one of our last hypes) databases normally allow to store large files. MongoDB for example has <a href="http://www.mongodb.org/display/DOCS/GridFS">GridFS</a>, But in this post we’re going to do it using <a href="http://couchdb.apache.org/">CouchDB</a>. With CouchDB we can attach documents within our database as simple attachments, just like email. </p>
<p>The api of CouchDB to upload an attachment is very simple. It’s a pure REST <a href="http://wiki.apache.org/couchdb/HTTP_Document_API#Attachments">api</a>. </p>
<p>In order to create the http connections directly with curl commands we can use libraries to automate this process. For example we can use a simple library shown in a previous <a href="http://gonzalo123.wordpress.com/2010/08/30/using-couchdb-as-filesystem-with-php/">post</a>. If we inspect the <a href="https://github.com/gonzalo123/nov-couchdb/blob/master/Nov_Http.php#L260">code</a> we will see that we’re creating a PUT request to store the file in our couchDB database. </p>
<p>Another cool thing we can do with PHP is to create a stream-wrapper to use standard filesystem functions for read/write/delete we can see a post about this <a href="http://gonzalo123.wordpress.com/2010/09/06/using-a-stream-wrapper-to-access-couchdb-attachments-with-php/">here</a>.</p>
<p>As we can see is very easy to use couchdb as filesystem. but we also can replicate our couchDB databases. Imagine that we have tho couchDB servers (host1 and host2). Each host has one database called fs. If we run the following command:</p>
<p><pre class="brush: bash;">
curl -X POST -H &quot;Content-Type: application/json&quot; http://host1:5984/_replicate -d '{&quot;source&quot;:&quot;cmr&quot;,&quot;target&quot;:&quot;http://host2:5984/fs&quot;,&quot;continuous&quot;:true}'
</pre></p>
<p>Our database will be replicated from host1 to host2 in a continuous mode. That’s means everytime we create/delete anything in host1, couchDB will replicate it to host2. A simple master-slave replica. </p>
<p>Now if we execute the same command in host2:</p>
<p><pre class="brush: bash;">
curl -X POST -H &quot;Content-Type: application/json&quot; http://host2:5984/_replicate -d '{&quot;source&quot;:&quot;cmr&quot;,&quot;target&quot;:&quot;http://host1:5984/fs&quot;,&quot;continuous&quot;:true}'
</pre></p>
<p>We have a multi-master replica system, cheap and easy to implement. As we can see we only need to install couchDB in each node, activate the replica and that’s all. Pretty straightforward, isn&#8217;t it?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1184/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1184&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2012/01/02/working-with-clouds-multi-master-file-system-replication-with-couchdb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Coding Katas, TDD and Katayunos</title>
		<link>https://gonzalo123.wordpress.com/2011/12/12/coding-katas-tdd-and-katayunos/</link>
		<comments>https://gonzalo123.wordpress.com/2011/12/12/coding-katas-tdd-and-katayunos/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 13:20:06 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[node.js]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1144</guid>
		<description><![CDATA[Summary of my way through the world of TDD and coding katas<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1144&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>2011 is about to finish, and I want to speak about my way through the world of TDD. In the beginning of the year appeared a new cool project called <a href="http://12meses12katas.com/">12meses12katas</a> (12 months &#8211; 12 katas). The aim of the project was to propose one coding kata per month, and allow to the people to publish their implementation of the kata over <a href="https://github.com/12meses12katas">github</a>. In the line of this project a crew of crazy <a href="https://twitter.com/#!/programania/katayuners/members">coders</a> started another cool project called <a href="http://katayunos.com/">Katayunos</a>. Katayunos is a small pun with the word Desayuno (Breakfast) and Coding Kata. It&#8217;s something similar than a code retreat. The purpose of the katayunos was to meet together in one place one saturday morning, have a breakfast and play with pair programming and TDD with one coding kata. Something too geek to explain to non-geek people, I known, but if you are reading this, It&#8217;s probable that your understand this <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Our first katayuno was in the cafeteria of one Hotel. One cold Saturday morning (a really cold <a href="http://www.twitpic.com/3say15">one</a> believe me). The main problem was that we didn&#8217;t have any electrical plug, so our pomodoros were marked by the laptop batteries.</p>
<p>After this cold first katayuno we achieve new places with wifi and those kind of luxuries. Those kind of events are really interesting because we meet together different people and different programming languages. I still remember when I played with c# one time (I still have the sulfur smell in my fingers <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ). </p>
<p>Basically the idea is: </p>
<ul>
<li>Choose a coding kata</li>
<li>Pomodoros of 25 minutes</li>
<li>Pair programming (change the couples with each iteration)</li>
<li>Have fun</li>
</ul>
<p>And now I&#8217;m going to show my 12 implementations of the 12 katas from 12meses12katas&#8217;s project:</p>
<p><strong>Jaunary: <a href="http://osherove.com/tdd-kata-1/">String-Calculator</a></strong><br />
A good kata for beginners. That&#8217;s a good one because the testing strategy is very clear and we can focus on Testing: Red (test NOK) -&gt; implement code -&gt; Green (test OK).<br />
My solution:  <a href="https://github.com/gonzalo123/Enero-String-Calculator/tree/master/gonzalo123">php + phpunit</a></p>
<p><strong>February: <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataRomanNumerals">Roman-Numerals</a></strong><br />
I really hate roman numerals after doing this kata <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
My solution: <a href="https://github.com/gonzalo123/Febrero-Roman-Numerals/tree/master/gonzalo123">python + pyunit</a></p>
<p><strong>March: <a href="http://www.codingdojo.org/cgi-bin/wiki.pl?KataFizzBuzz">FizzBuzz</a></strong><br />
A famous kata. A Really simple one. Because of that we can focus on the TDD (baby steps, refactoring, &#8230;)<br />
My solution: <a href="https://github.com/gonzalo123/Marzo-FizzBuzz/tree/master/gonzalo123">php + phpunit</a><br />
I also wrote a <a href="http://kcy.me/65dp">post</a> with a crazy dynamic classes and the implementation of FizzBuzz kata with those dinamic classes:</p>
<p><strong>April: <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataBowling">Bowling</a></strong><br />
My problem was that I didn&#8217;t know the rules of Bowling so I needed to learn how to play Bowling first.<br />
My solution: <a href="https://github.com/gonzalo123/Abril-Bowling/tree/master/gonzalo123">php + phpunit</a></p>
<p><strong>May: <a href="http://agilismo.es/codekatas/109-katalonja">KataLonja</a></strong><br />
A strange kata. I like it because it&#8217;s not a theoretical one. It&#8217;s close to a real problem.<br />
My solution: <a href="https://github.com/gonzalo123/Mayo-KataLonja/tree/master/gonzalo123">php + phpunit</a></p>
<p><strong>June: <a href="http://codekata.pragprog.com/2007/01/kata_twenty_one.html">Simple-Lists</a></strong><br />
It was my first kata with javascript and node.js.<br />
My solution: <a href="https://github.com/gonzalo123/Junio-Simple-Lists/tree/master/gonzalo123">node.js + nodeunit</a> (with John Resig&#8217;s class implementation)</p>
<p><strong>July: <a href="http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata">Prime-Factors</a></strong><br />
Another famous one: Prime factors.<br />
My solution: <a href="https://github.com/gonzalo123/Julio-Prime-Factors/tree/master/gonzalo123">node.js + nodeunit</a></p>
<p><strong>August: <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataMinesweeper">Minesweeper</a></strong><br />
An implementation of the famous computer game Minesweeper.<br />
My solution: <a href="https://github.com/gonzalo123/Agosto-Minesweeper/tree/master/gonzalo123">php + phpunit</a></p>
<p><strong>October: <a href="http://codekata.pragprog.com/2007/01/kata_two_karate.html">Karate-Chop</a></strong><br />
Dual solution. With php and JavaScript (with node.js)<br />
My solution: <a href="https://github.com/gonzalo123/Octubre-Karate-Chop/tree/master/gonzalo123">php + phpunit and node.js + nodeunit</a></p>
<p><strong>November: <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataPotter">KataPotter</a></strong><br />
This time I will use coffeescript instead of pure js<br />
My solution: <a href="https://github.com/gonzalo123/Noviembre-KataPotter/tree/master/gonzalo123">node.js + coffeeScript + jasmine</a></p>
<p><strong>December: <a href="http://agilismo.es/2011/12/06/pomodorokata/">PomodoroKata</a></strong><br />
CoffeeScript again. One pomodoro is one pomodoro. Let&#8217;s build a pomodoro timer in a pomodoro.<br />
My solution: <a href="https://github.com/gonzalo123/Diciembre-PomodoroKata/tree/master/gonzalo123">node.js + coffeeScript + jasmine</a></p>
<p>So, what are you waiting for to create a local group and clone the katayuno in your city? It&#8217;s very easy: broadcast the event over twitter, pick a place, pick a kata <a href="http://www.flickr.com/photos/ggalmazor/sets/72157626032025541/">and</a> <a href="http://www.flickr.com/photos/joserra/sets/72157626021532617/">enjoy</a>.</p>
<p>Regards, <a href="https://twitter.com/#!/gonzalo123">Gonzalo</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1144&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/12/12/coding-katas-tdd-and-katayunos/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with the new PHP5.4 features</title>
		<link>https://gonzalo123.wordpress.com/2011/11/28/playing-with-the-new-php5-4-features/</link>
		<comments>https://gonzalo123.wordpress.com/2011/11/28/playing-with-the-new-php5-4-features/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 12:49:24 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1126</guid>
		<description><![CDATA[PHP5.4 it's close. It's time to start playing with the new cool features.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1126&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>PHP5.4 it&#8217;s close and it&#8217;s time to start playing with the new cool features. I&#8217;ve created a new Virtual Machine to play with the new features available within PHP5.4. I wrote a <a href="http://gonzalo123.wordpress.com/2011/07/04/new-features-in-php5-4-alpha1/" title="New features in PHP5.4&nbsp;alpha1">post</a> with the most exciting features (at least for me) when I saw the feature list in the alpha version. Now the Release Candidate is with us, so it&#8217;s the time of start playing with them. I also discover really cool features that I pass over in my first review</p>
<p>Let&#8217;s start:</p>
<p><strong>Class member access on instantiation.</strong></p>
<p>Cool!<br />
<pre class="brush: php;">
class Human
{
    function __construct($name)
    {
        $this-&gt;name = $name;
    }

    public function hello()
    {
        return &quot;Hi &quot; . $this-&gt;name;
    }
}

// old style
$human = new Human(&quot;Gonzalo&quot;);
echo $human-&gt;hello();

// new cool style
echo (new Human(&quot;Gonzalo&quot;))-&gt;hello();
</pre></p>
<p><strong>Short array syntax</strong><br />
Yeah!<br />
<pre class="brush: php;">
$a = [1, 2, 3];
print_r($a);
</pre></p>
<p><strong>Support for Class::{expr}() syntax</strong><br />
<pre class="brush: php;">
foreach ([new Human(&quot;Gonzalo&quot;), new Human(&quot;Peter&quot;)] as $human) {
    echo $human-&gt;{'hello'}();
}
</pre></p>
<p><strong>Indirect method call through array</strong><br />
<pre class="brush: php;">
$f = [new Human(&quot;Gonzalo&quot;), 'hello'];
echo $f();
</pre></p>
<p><strong>Callable typehint</strong><br />
<pre class="brush: php;">
function hi(callable $f) {
    $f();
}

hi([new Human(&quot;Gonzalo&quot;), 'hello']);
</pre></p>
<p><strong>Traits</strong><br />
<pre class="brush: php;">
trait FlyMutant {
    public function fly() {
        return 'I can fly!';
    }
}

class Mutant extends Human {
    use FlyMutant;
}

$mutant = new Mutant(&quot;Storm&quot;);
echo $mutant-&gt;fly();
</pre></p>
<p><strong>Array dereferencing support</strong><br />
<pre class="brush: php;">
function data() {
    return ['name' =&gt; 'Gonzalo', 'surname' =&gt; 'Ayuso'];
}

echo data()['name'];
</pre></p>
<p>IDEs don&#8217;t support (yet) those features. That&#8217;s means IDEs will mark those new features as syntax errors but I hope that they will support them soon.<br />
More info <a href="http://php.webtutor.pl/en/2011/09/27/whats-new-in-php-5-4-a-huge-list-of-major-changes/">here</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1126/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1126&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/11/28/playing-with-the-new-php5-4-features/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with Request objects in PHP (II). Back to the past</title>
		<link>https://gonzalo123.wordpress.com/2011/11/07/working-with-request-objects-in-php-ii-back-to-the-past/</link>
		<comments>https://gonzalo123.wordpress.com/2011/11/07/working-with-request-objects-in-php-ii-back-to-the-past/#comments</comments>
		<pubDate>Mon, 07 Nov 2011 13:48:44 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1108</guid>
		<description><![CDATA[Second part of RequestObject library. Now we will allow to use "variable injection" in our script like old times.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1108&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In one of my last post “<a href="http://gonzalo123.wordpress.com/2011/10/17/working-with-request-objects-in-php/" title="Working with Request objects in PHP">Working with request objects in PHP</a>”, I wrote a simple library to handle request objects. According that post let&#8217;s do a bit of history of PHP. In the early years of PHP (PHP3 &#8211; PHP4) one of the cool features of PHP was the &#8220;variable injection&#8221; inside our projects with <a href="http://es2.php.net/manual/en/security.globals.php">register_globals</a>=on. If you had the following a url:</p>
<p><code>index.php?parameter1=Hi</code></p>
<p>Your script had magically a variable called $parameter1 with the value “Hi”. This feature has horrible security problems, if our user can inject variables in our scripts, especially with a loose typing program language like PHP. Because of that we all swap from those injected variables to get the value from $_POST and $_GET superglobals. In fact &#8220;injected variables&#8221; are disabled long time ago within PHP configuration.</p>
<p>Nowadays we <a href="http://www.phparch.com/2010/07/never-use-_get-again/">don’t</a> use $_POST $_GET superglobals directly. We need to filter the input. Because of that I wrote <a href="https://github.com/gonzalo123/RequestObject/blob/master/RequestObject.php">RequestObject</a> library. Now we’re going to back to the past and allow the use of injected variables, but filtered.</p>
<p>RequestObject has now an extra public function called getFilteredParameters. This function returns an array with all already filtered input parameters. So if we use “<a href="http://php.net/manual/function.extract.php">extract</a>” function we can create variables for each input parameters, but with the filtered values:</p>
<p><pre class="brush: php;">
class Request extends RequestObject
{
    /** @cast string */
    public $param1;
    /**
     * @cast string
     * @default default value
     */
    public $param2;
}

$request = new Request();
extract($request-&gt;getFilteredParameters());

echo &quot;param1: &lt;br/&gt;&quot;;
var_dump($param1);
echo &quot;&lt;br/&gt;&quot;;

echo &quot;param2: &lt;br/&gt;&quot;;
var_dump($param2);
echo &quot;&lt;br/&gt;&quot;;
</pre></p>
<p>Full library available on github <a href="https://github.com/gonzalo123/RequestObject/">here</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1108&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/11/07/working-with-request-objects-in-php-ii-back-to-the-past/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Talk about node.js and WebSockets</title>
		<link>https://gonzalo123.wordpress.com/2011/10/24/talk-about-node-js-and-websockets/</link>
		<comments>https://gonzalo123.wordpress.com/2011/10/24/talk-about-node-js-and-websockets/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 11:38:25 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[node.js]]></category>
		<category><![CDATA[socket.io]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Websockets]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[talks]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1095</guid>
		<description><![CDATA[Talk about node.js and WebSockets<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1095&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last friday I spoke about node.js and Websockets with the people of <a href="http://themelee.org/post/11580408703/melee-node-js-html5-websockets-21-octubre">The Mêlée</a>. The talk was an introduction to <a href="http://nodejs.org/">node.js</a> and focused in the new HTML5 feature: <a href="http://dev.w3.org/html5/websockets/">the WebSockets</a>.</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/9813277' width='604' height='495'></iframe>
<p>When I spoke about Websockets I also introduced the great library <a href="http://socket.io/">socket.io</a>. The jQuery of WebSockets.</p>
<p><a href="http://gonzalo123.files.wordpress.com/2011/10/charlanodejs.jpg"><img src="http://gonzalo123.files.wordpress.com/2011/10/charlanodejs.jpg?w=300&#038;h=224" alt="" title="Me speaking. Photo thanks to @programania" width="300" height="224" class="aligncenter size-medium wp-image-1098" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1095/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1095&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/10/24/talk-about-node-js-and-websockets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:thumbnail url="http://gonzalo123.files.wordpress.com/2011/10/charlanodejs.jpg?w=150" />
		<media:content url="http://gonzalo123.files.wordpress.com/2011/10/charlanodejs.jpg?w=150" medium="image">
			<media:title type="html">charlaNodeJs</media:title>
		</media:content>

		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>

		<media:content url="http://gonzalo123.files.wordpress.com/2011/10/charlanodejs.jpg?w=300" medium="image">
			<media:title type="html">Me speaking. Photo thanks to @programania</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with Request objects in PHP</title>
		<link>https://gonzalo123.wordpress.com/2011/10/17/working-with-request-objects-in-php/</link>
		<comments>https://gonzalo123.wordpress.com/2011/10/17/working-with-request-objects-in-php/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 12:40:04 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1065</guid>
		<description><![CDATA[Normally when we work with web applications we need to handle Request objects. Request is the input of our applications. Filter Input-Escape Output is the rule. Frameworks filter them for us, but not all are frameworks. Here a small library to filter and validate Request input.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1065&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Normally when we work with web applications we need to handle Request objects. Requests are the input of our applications. According to the golden rule of security:</p>
<blockquote><p>Filter Input-Escape Output</p></blockquote>
<p>We cannot use $_GET and $_POST superglobals. OK we can use then but we <a href="http://www.phparch.com/2010/07/never-use-_get-again/">shouldn’t</a> use them. Normally web frameworks do this work for us, but not all is a framework.</p>
<p>Recently I have worked in a small project without any framework. In this case I also need to handle Request objects. Because of that I have built this small library. Let me show it.</p>
<p>Basically the idea is the following one. I want to filter my inputs, and I don&#8217;t want to remember the whole name of every input variables. I want to define the Request object once and use it everywhere. Imagine a small application with a simple input called param1. The URL will be:</p>
<p><code>test1.php?param1=11212</code></p>
<p>and we want to build this simple script:<br />
<pre class="brush: php;">
echo &quot;param1: &quot; . $_GET['param1'] . '&lt;p/&gt;';
</pre></p>
<p>The problem with this script is that we aren&#8217;t filtering input. And we also need to remember the parameter name is param1. If we need to use param1 parameter in another place we need to remember its name is param1 and not Param1 or para1. It can be obvious but it&#8217;s easy to make mistakes. </p>
<p>My proposal is the following one. I create a simple PHP class called Request1 extending RequestObject object:</p>
<h2>Example 1: simple example</h2>
<p><pre class="brush: php;">
class Request1 extends RequestObject
{
    public $param1;
}
</pre></p>
<p>Now if we create an instance of Request1, we can use the following code:<br />
<pre class="brush: php;">
$request = new Request1();
echo &quot;param1: &quot; . $request-&gt;param1 . '&lt;p/&gt;';
</pre></p>
<p>I&#8217;m not going to explain the magic now, but with this simple script we will filter the input to the default type (string) and we will get the following outcomes:</p>
<p><code><br />
test1.php?param1=11212<br />
param1: 11212</p>
<p>test1.php?param1=hi<br />
param1: hi<br />
</code></p>
<p>Maybe is hard to explain with words but with examples it&#8217;s more easy to show you what I want:</p>
<h2>Example 2: data types and default values</h2>
<p><pre class="brush: php;">
class Request2 extends RequestObject
{
    /**
     * @cast string
     */
    public $param1;
    /**
     * @cast string
     * @default default value
     */
    public $param2;
}

$request = new Request2();

echo &quot;param1: &lt;br/&gt;&quot;;
var_dump($request-&gt;param1);
echo &quot;&lt;br/&gt;&quot;;

echo &quot;param2: &lt;br/&gt;&quot;;
var_dump($request-&gt;param2);
echo &quot;&lt;br/&gt;&quot;;
</pre></p>
<p>Now we are will filter param1 parameter to string and param2 to string to but we will assign a default variable to the parameter if we don&#8217;t have a user input.</p>
<p><code><br />
test2.php?param1=hi&amp;param2=1</p>
<p>param1: string(2) "hi"<br />
param2: string(1) "1"</p>
<p>test2.php?param1=1&amp;param2=hi</p>
<p>param1: string(1) "1"<br />
param2: string(2) "hi"</p>
<p>test2.php?param1=1<br />
param1: string(1) "1"<br />
param2: string(13) "default value"<br />
</code></p>
<h2>Example 3: validadors</h2>
<p><pre class="brush: php;">
class Request3 extends RequestObject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;

    protected function validate_param1(&amp;$value)
    {
        $value = strrev($value);
    }
    
    protected function validate_param2($value)
    {
        if ($value == 1) {
            return false;
        }
    }
}
try {
    $request = new Request3();

    echo &quot;param1: &lt;br/&gt;&quot;;
    var_dump($request-&gt;param1);
    echo &quot;&lt;br/&gt;&quot;;

    echo &quot;param2: &lt;br/&gt;&quot;;
    var_dump($request-&gt;param2);
    echo &quot;&lt;br/&gt;&quot;;
} catch (RequestObjectException $e) {
    echo $e-&gt;getMessage();
    echo &quot;&lt;br/&gt;&quot;;
    var_dump($e-&gt;getValidationErrors());
}
</pre></p>
<p>Now a complex example. param1 is a string and param2 is an integer, but we also will validate them. We will alter the param1 value (a simple <a href="http://php.net/manual/en/function.strrev.php">strrev</a>) and we also will raise an exception if param2 is equal to 1</p>
<p><code><br />
test3.php?param2=2&amp;param1=hi<br />
param1: string(2) "ih"<br />
param2: int(2)</p>
<p>test3.php?param1=hola&amp;param2=1<br />
Validation error<br />
array(1) { ["param2"]=&gt; array(1) { ["value"]=&gt; int(1) } }<br />
</code></p>
<h2>Example 4: Dynamic validations</h2>
<p><pre class="brush: php;">
class Request4 extends RequestObject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;
}

$request = new Request4(false); // disables perform validation on contructor
                               // it means it will not raise any validation exception
$request-&gt;appendValidateTo('param2', function($value) {
        if ($value == 1) {
            return false;
        }
    });

try {
    $request-&gt;validateAll(); // now we perform the validation

    echo &quot;param1: &lt;br/&gt;&quot;;
    var_dump($request-&gt;param1);
    echo &quot;&lt;br/&gt;&quot;;

    echo &quot;param2: &lt;br/&gt;&quot;;
    var_dump($request-&gt;param2);
    echo &quot;&lt;br/&gt;&quot;;
} catch (RequestObjectException $e) {
    echo $e-&gt;getMessage();
    echo &quot;&lt;br/&gt;&quot;;
    var_dump($e-&gt;getValidationErrors());
}
</pre></p>
<p>More complex example. Param1 will be cast as string and param2 as integer again, same validation to param2 (exception if value equals to 1), but now validation rule won&#8217;t be set in the definition of the class. We will append dynamically after the instantiation of the class.</p>
<p><code><br />
test4.php?param1=hi&amp;param2=2<br />
param1: string(4) "hi"<br />
param2: int(2)</p>
<p>test4.php?param1=hola&amp;param2=1<br />
Validation error<br />
array(1) { ["param2"]=&gt; array(1) { ["value"]=&gt; int(1) } }<br />
</code></p>
<h2>Example 5: Arrays and default params</h2>
<p><pre class="brush: php;">
class Request5 extends RequestObject
{
    /** @cast arrayString */
    public $param1;

    /** @cast integer */
    public $param2;

    /**
     * @cast arrayString
     * @defaultArray &quot;hello&quot;, &quot;world&quot;
     */
    public $param3;

    protected function validate_param2(&amp;$value)
    {
        $value++;
    }
}

$request = new Request5();

echo &quot;&lt;p&gt;param1: &lt;/p&gt;&quot;;
var_dump($request-&gt;param1);

echo &quot;&lt;p&gt;param2: &lt;/p&gt;&quot;;
var_dump($request-&gt;param2);

echo &quot;&lt;p&gt;param3: &lt;/p&gt;&quot;;
var_dump($request-&gt;param3);
</pre></p>
<p>Now a simple example but input parameters allow arrays and default values.</p>
<p><code><br />
test5.php?param1[]=1&amp;param1[]=2&amp;param2[]=hi<br />
param1: array(2) { [0]=&gt; int(1) [1]=&gt; int(2) }<br />
param2: int(1)<br />
param3: array(2) { [0]=&gt; string(5) "hello" [1]=&gt; string(5) "world" }</p>
<p>test5.php?param1[]=1&amp;param1[]=2&amp;param2=2<br />
param1: array(2) { [0]=&gt; string(1) "1" [1]=&gt; string(1) "2" }<br />
param2: int(3)<br />
param3: array(2) { [0]=&gt; string(5) "hello" [1]=&gt; string(5) "world" }<br />
</code></p>
<h2>RequestObject</h2>
<p>The idea of RequestObject class is very simple. When we create an instance of the class (in the constructor) we filter the input request (GET or POST depending on REQUEST_METHOD) with <a href="http://php.net/manual/en/function.filter-var-array.php">filter_var_array</a> and <a href="http://es2.php.net/manual/en/function.filter-var.php">filter_var</a> functions according to the rules defined as annotations in the RequestObject class. Then we populate the member variables of the class with the filtered input. Now we can use to the member variables, and auto-completion will work perfectly with our favourite IDE with the parameter name. OK. I now. I violate encapsulation principle allowing to access directly to the public member variables. But IMHO the final result is more clear than creating an accessor here. But if it creeps someone out, we would discuss another solution <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Full code here on <a href="https://github.com/gonzalo123/RequestObject">github</a></p>
<p>What do you think?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1065/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1065/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1065/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1065&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/10/17/working-with-request-objects-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Display errors on screen even with display errors = off with PHP</title>
		<link>https://gonzalo123.wordpress.com/2011/10/10/display-errors-on-screen-even-with-display-errors-off-in-php/</link>
		<comments>https://gonzalo123.wordpress.com/2011/10/10/display-errors-on-screen-even-with-display-errors-off-in-php/#comments</comments>
		<pubDate>Mon, 10 Oct 2011 12:41:48 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[error_log]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1067</guid>
		<description><![CDATA[Sometimes we work with shared hostings, without access to error_log file. With this script we will see how to display errors on screen even with display_errors = Off. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1067&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last month I was in a coding kata <a href="http://katayunos.com/">session</a> playing with <a href="http://osherove.com/tdd-kata-1/">StingCalculator</a>, and between iteration and iteration we were taking about the problems of shared hostings. <strong>Shared hosting</strong> are cheap, but normally they don&#8217;t allow us the use some kind of features. For example we <strong>cannot see the error log</strong>. That’s a problem when we need to see what happens within our application. Normally I work with my own servers, and I have got full access to error logs. But if we cannot see the error log and the server is configured with <a href="http://es.php.net/manual/en/errorfunc.configuration.php#ini.display-errors">display errors = off</a> in php.ini (typical configuration in shared hosting), we have a problem. </p>
<p>One of my post came to my mind “<a href="http://gonzalo123.wordpress.com/2011/05/09/real-time-monitoring-php-applications-with-websockets-and-node-js/">Real time monitoring PHP applications with websockets and node.js</a>”. Basically we can solve the problem using this technique, but if we are speaking about shared hosting without error log access, it’s very probably that we cannot install a node.js server or even use sockets functions. So it’s not “Real” solution to our problem.</p>
<p>The idea is create a variation of the original script (one kind of script’s Spin-off <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). In this scprit we will capture errors and exceptions and show them in script at the end of the script. We don’t have access to the error log but we will show it in the browser.</p>
<p>Imagine the following script:<br />
<pre class="brush: php;">
$a = 1/0;
throw new Exception(&quot;myException&quot;);
echo &quot;hi&quot;;
</pre></p>
<p>It will show one warning (1/0) and one exception (myException)</p>
<ul>
<li>Warning: Division by zero</li>
<li>Fatal error: Uncaught exception &#8216;Exception&#8217; with message &#8216;myException&#8217;</li>
</ul>
<p>If we change php.ini show errors = off we will see a nice white screen.</p>
<p>The idea is add to the script:<br />
<pre class="brush: php;">
include('ErrorSniffer.php');
ErrorSniffer::factory('127.0.0.1');

$a = 1/0;
throw new Exception(&quot;myException&quot;);
echo &quot;hi&quot;;
</pre></p>
<p>Now with with <a href="https://github.com/gonzalo123/ErrorSniffer">ErrorSniffer</a> library we will see a nice output, even with display errors = off.<br />
I also add a IP in the class constructor to restrict the output message to one IP. The idea is to place this script at production, so we don’t want to expose error messages to whole users.</p>
<p>If we see the source code of ErrorSniffer class we a constructor like this:<br />
<pre class="brush: php;">
    public function __construct($restingToIp)
    {
        if ($this-&gt;getip() == $restingToIp) {
            self::register_exceptionHandler($this);
            self::set_error_handler($this);
            self::register_shutdown_function($this);
        }
    }

    private static function set_error_handler(ErrorSniffer &amp;$that)
    {
        set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&amp;$that) {
                $type = ErrorSniffer::getErrorName($errno);
                $that-&gt;registerError(array('type' =&gt; $type, 'message' =&gt; $errstr, 'file' =&gt; $errfile, 'line' =&gt; $errline));
                return false;
        });
    }

    private static function register_exceptionHandler(ErrorSniffer &amp;$that)
    {
        set_exception_handler(function($exception) use (&amp;$that) {
                $exceptionName = get_class($exception);
                $message = $exception-&gt;getMessage();
                $file  = $exception-&gt;getFile();
                $line  = $exception-&gt;getLine();
                $trace = $exception-&gt;getTrace();
    
                $that-&gt;registerError(array('type' =&gt; 'EXCEPTION', 'exception' =&gt; $exceptionName, 'message' =&gt; $message, 'file' =&gt; $file, 'line' =&gt; $line, 'trace' =&gt; $trace));
                return false;
        });
    }

    private static function register_shutdown_function(ErrorSniffer &amp;$that)
    {
        register_shutdown_function(function() use (&amp;$that) {
                $error = error_get_last();

                if ($error['type'] == E_ERROR) {
                    $type = ErrorSniffer::getErrorName($error['type']);
                    $that-&gt;registerError(array('type' =&gt; $type, 'message' =&gt; $error['message'], 'file' =&gt; $error['file'], 'line' =&gt; $error['line']));
                }

                $that-&gt;printErrors();
        });
    }
</pre></p>
<p>As we can see we will catch errors and exceptions, we populate the member variable $errors and we also use <a href="http://php.net/manual/en/function.register-shutdown-function.php">register_shutdown_function</a> to show information on shutdown.</p>
<p>You can see the full script at github <a href="https://github.com/gonzalo123/ErrorSniffer">here</a>.</p>
<p>What do you think?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1067/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1067/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1067/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1067&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/10/10/display-errors-on-screen-even-with-display-errors-off-in-php/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a small microframework with PHP (Part 2). Command line interface</title>
		<link>https://gonzalo123.wordpress.com/2011/08/29/building-a-small-microframework-with-php-part-2-command-line-interface/</link>
		<comments>https://gonzalo123.wordpress.com/2011/08/29/building-a-small-microframework-with-php-part-2-command-line-interface/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 12:32:30 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[microframework]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1045</guid>
		<description><![CDATA[improving our small micro-framework adding a command line interface<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1045&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://gonzalo123.wordpress.com/2011/08/22/building-a-small-microframework-with-php/">last post</a> we spoke about building a small microframework with PHP. The main goal of this kind of framework was to be able to map urls to plain PHP classes and become those classes easily testeable with PHPUnit. Now we&#8217;re going to take a step forward. Sometimes we need to execute the script from command line, for example if we need to use them in a crontab file. OK. We can use curl and perform a simple http call to the webserver. But it&#8217;s pretty straightforward to create a command line interface (CLI) for our microframework. Zend Framework and Symfony has a great console tools. I&#8217;ve used <a href="http://framework.zend.com/manual/en/zend.console.getopt.html">Zend_Console_Getopt</a> in a project and is really easy to use and well documented. But now we&#8217;re going to build a command line interface from scratch. </p>
<p>We are going to reuse a lot of code from the earlier post, because of that we are going to encapsulate the code in a class (<a href="http://goo.gl/QpDP">DRY</a>). </p>
<p>We will use the <a href="http://php.net/manual/es/function.getopt.php">getopt</a> function from PHP&#8217;s function set.</p>
<p><pre class="brush: php;">
$sortOptions = &quot;&quot;;
$sortOptions .= &quot;c:&quot;;
$sortOptions .= &quot;f:&quot;;
$sortOptions .= &quot;v::&quot;;
$sortOptions .= &quot;h::&quot;;

$options = getopt($sortOptions);
</pre></p>
<p>Then we need to take the paramaters from $GLOBALS['argv'] superglobal according with the options. I use the following hack to prepare $GLOBALS['argv']:</p>
<p><pre class="brush: php;">
foreach( $options_array as $o =&gt; $a ) {
    while($k=array_search(&quot;-&quot;. $o. $a, $GLOBALS['argv'])) {
        if($k) {
            unset($GLOBALS['argv'][$k]);
        }
    }
    while($k=array_search(&quot;-&quot; . $o, $GLOBALS['argv'])) {
        if($k) {
            unset($GLOBALS['argv'][$k]);
            unset($GLOBALS['argv'][$k+1]);
        }
    }
}
$GLOBALS['argv'] = array_merge($GLOBALS['argv']);
</pre></p>
<p>And now we get the params into $param_arr array.</p>
<p><pre class="brush: php;">
$param_arr = array();
$lenght = count((array)$GLOBALS['argv']);
if ($lenght &gt; 0) {
    for ($i = 1; $i &lt; $lenght; $i++) {
        if (isset($GLOBALS['argv'][$i])) {
            list($paramName, $paramValue) = explode(&quot;=&quot;, $GLOBALS['argv'][$i], 2);
            $param_arr[$paramName] = $paramValue;
        }
    }
}
</pre></p>
<p>Now we can get className and functionName:</p>
<p><pre class="brush: php;">
$className    = !array_key_exists('c', $options) ?: $options['c'];
$functionName = !array_key_exists('f', $options) ?: $options['f'];
</pre></p>
<p>We add a &#8220;usage&#8221; parameter:</p>
<p><pre class="brush: php;">
if (array_key_exists('h', $options)) {
     $usage = &lt;&lt;&lt;USAGE
Usage: cli [options] [-c] &lt;class&gt; [-f] &lt;function&gt; [args...]

Options:
-h Print this help
-v verbose mode
\n
USAGE;
    echo $usage;
    exit;
}
</pre></p>
<p>Now we can invoke the function with call_user_func_array</p>
<p><pre class="brush: php;">
return call_user_func_array(array($className, $functionName), $this-&gt;realParams);
</pre></p>
<p>As you can see, instead of using $param_arr as parameters array, We need to create an extra $realParams array. The aim of this realParams arrays is to use call_user_func_array with named parameters. In getRealParams function we use reflection to see what are the real parameters of our function and use only those parameters form in the correct order instead. With this trick we will allow to the user to use the parameters in the his desired order, and without forcing to use the real order of our function.</p>
<p><pre class="brush: php;">
    private function getRealParams($params)
    {
        $realParams = array();
        $class = new ReflectionClass(new $this-&gt;className);
        $reflect = $class-&gt;getMethod($this-&gt;functionName);

        foreach ($reflect-&gt;getParameters() as $i =&gt; $param) {
            $pname = $param-&gt;getName();
            if ($param-&gt;isPassedByReference()) {
                /// @todo shall we raise some warning?
            }
            if (array_key_exists($pname, $params)) {
                $realParams[] = $params[$pname];
            } else if ($param-&gt;isDefaultValueAvailable()) {
                $realParams[] = $param-&gt;getDefaultValue();
            } else {
                throw new Exception(&quot;{$this-&gt;className}::{$this-&gt;functionName}() param: missing param: {$pname}&quot;);
            }
        }
        return $realParams;
    }
</pre></p>
<p>And now we can use our microframework from the command line:<br />
<pre class="brush: bash;">
./cli -c 'Demo\Foo' -f hello
Hello

./cli -c Demo\\Foo -f getUsers
[&quot;Gonzalo&quot;,&quot;Peter&quot;]

./cli -c Demo\\Foo -f helloName name=Gonzalo surname=Ayuso
Hello Gonzalo Ayuso
</pre></p>
<p>Full code on <a href="https://github.com/gonzalo123/microFramework">github</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1045/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1045/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1045/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1045&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/08/29/building-a-small-microframework-with-php-part-2-command-line-interface/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a small microframework with PHP</title>
		<link>https://gonzalo123.wordpress.com/2011/08/22/building-a-small-microframework-with-php/</link>
		<comments>https://gonzalo123.wordpress.com/2011/08/22/building-a-small-microframework-with-php/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 13:22:02 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[microframework]]></category>

		<guid isPermaLink="false">http://gonzalo123.wordpress.com/?p=1020</guid>
		<description><![CDATA[Creating a small microframework with PHP<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1020&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Nowadays microframewors are very popular. Since Blake Mizerany created <a href="http://www.sinatrarb.com/">Sinatra</a> (Ruby), we have a lot of Sinatra clones in PHP world. Probably the most famous (and a really good one) is <a href="http://silex-project.org/">Silex</a>. But we also have several ones, such as <a href="http://www.limonade-php.net/">Limonade</a>, <a href="http://gluephp.com/">GluePHP</a> and <a href="http://www.slimframework.com/">Slim</a>. Those frameworks are similar. We define routes and we connect those routes to callbacks:</p>
<p>For example: </p>
<blockquote><p>&#8216;/hello/{name}&#8217; =&gt; function ($name) {return &#8220;Hello $name&#8221;;}</p></blockquote>
<p>Those microframeworks use the new PHP 5.3 callback features. It&#8217;s easy to build prototypes with those frameworks. I&#8217;ve used silex for a small prototype and I&#8217;m really happy with it. But I have a little problem. Each time I need to create a new route I need to create the route and create the callback. The business logic is inside the callback, but I need to tell to the framework where is it with the router. That&#8217;s means code de callback and write the router. This way of work has advantages. You can change the routes without changing the business logic. I feel comfortable with it in small projects, but when it scales it&#8217;s difficult to manage (at least for me). <a href="http://symfony.com/">Symfony2</a> has a great way to create <a href="http://symfony.com/doc/current/book/routing.html">routes</a>, with inheritance, catching and things like that, but sometimes I dont&#8217;t feel confortable with it. Because of that I have done this small microframework experiment. The idea is drop the router and create it depending on the filesystem. The first idea was inside this postit:</p>
<p><a href="http://gonzalo123.files.wordpress.com/2011/08/microframework1.jpg"><img src="http://gonzalo123.files.wordpress.com/2011/08/microframework1.jpg?w=297&#038;h=300" alt="" title="microFramework" width="297" height="300" class="aligncenter size-medium wp-image-1024" /></a></p>
<p>Yes I now. If I want to change the class inside the filesystem, I need to change the urls. As an experiment, I&#8217;ve created a small microframework. The idea the following one:</p>
<ul>
<li>.htaccess to redirect every request to index.php</li>
<li>a set of classes (plain php classes)</li>
<li>index.php will invoke the required class&#8217; function</li>
<li>after invoking the required function index.php will convert the output to the format selected</li>
</ul>
<p><a href="http://gonzalo123.files.wordpress.com/2011/08/folder.png"><img src="http://gonzalo123.files.wordpress.com/2011/08/folder.png?w=604" alt="" title="folder"   class="aligncenter size-full wp-image-1022" /></a></p>
<p>Basically index.php will follow the following script:<br />
<pre class="brush: php;">
setUpAutoload();
list($className, $functionName, $format, $params) = decodeUri(getUri());
$realParams = getRealParams($className, $functionName, $params);
echo format($format, call_user_func_array(array($className, $functionName), $realParams));
</pre></p>
<p>Here you have the full index.php code:<br />
<pre class="brush: php;">
function call_user_func_named($className, $obj, $function, $params)
{
    $class = new ReflectionClass($obj);
    $reflect = $class-&gt;getMethod($function);

    $realParams = array();
    foreach ($reflect-&gt;getParameters() as $i =&gt; $param) {
        $pname = $param-&gt;getName();
        if ($param-&gt;isPassedByReference()) {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params)) {
            $realParams[] = $params[$pname];
        } else if ($param-&gt;isDefaultValueAvailable()) {
            $realParams[] = $param-&gt;getDefaultValue();
        } else {
            throw new Exception(&quot;{$className}::{$function}() param: missing param: {$pname}&quot;);
        }
    }

    return call_user_func_array(array(new $obj, $function), $realParams);
}

function decodeUri($uri)
{
    $conf = $params = array();
    $functionName = $format = null;

    $parsedUrl = parse_url($uri);
    $path = $parsedUrl['path'];
    if (isset($parsedUrl['query'])) {
        $query = $parsedUrl['query'];
        $params = array();
        $pairs = explode('&amp;', $query);
        foreach ($pairs as $pair) {
            if (trim($pair) == '') {
                continue;
            }
            list($key, $value) = explode('=', $pair);
            $params[$key] = urldecode($value);
        }
    }
    $arr = explode('/', $path);

    for ($i = 0; $i &lt; count($arr); $i++) {
        $elem = $arr[$i];
        if (strpos($elem, '.') !== false) {
            list($functionName, $format) = explode(&quot;.&quot;, $elem);
            continue;
        } else {
            if ($elem != '') $conf[] = ucfirst($elem);
        }
    }

    $className = implode('\\', $conf);
    return array($className, $functionName, $format, $params);
}

function format($format, $out)
{
    switch ($format) {
        case 'json':
            header('Cache-Control: no-cache, must-revalidate');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Content-type: application/json');
            return json_encode($out);
        case 'html':
        case 'htm':
            header('Cache-Control: no-cache, must-revalidate');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
            header('Content-type: Content-Type: text/html');
            return (string)$out;
        case 'txt':
        case 'ajax':
            header('Content-type: text/plain; charset=utf-8');
            return (string)$out;
        case 'css':
            header('Content-type: text/css');
            return (string)$out;
        case 'js':
            header('Content-type: application/javascript');
            return (string)$out;
        case 'jsonp':
            $cbk = filter_input(INPUT_GET, '_cbk', FILTER_SANITIZE_STRING);
            if ($cbk == '') {
                $cbk = 'cbk';
            }

            header('Content-type: text/javascript; charset=utf-8');
            return &quot;{$cbk}(&quot; . json_encode($out) . &quot;);&quot;;
        default:
            throw new Exception(&quot;Undefined format&quot;);
    }
}

function getRealParams($className, $functionName, $params)
{
    $realParams = array();
    $class = new \ReflectionClass(new $className);
    $reflect = $class-&gt;getMethod($functionName);

    foreach ($reflect-&gt;getParameters() as $i =&gt; $param) {
        $pname = $param-&gt;getName();
        if ($param-&gt;isPassedByReference()) {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params)) {
            $realParams[] = $params[$pname];
        } else if ($param-&gt;isDefaultValueAvailable()) {
            $realParams[] = $param-&gt;getDefaultValue();
        } else {
            throw new Exception(&quot;{$className}::{$functionName}() param: missing param: {$pname}&quot;);
        }
    }
    return $realParams;
}

function setUpAutoload()
{
    spl_autoload_register(function ($class)
        {
            $class = str_replace('\\', '/', $class) . '.php';
            if (is_file($class)) {
                require_once($class);
            } else {
                throw new Exception(&quot;{$class} does not exists&quot;);
            }
        }
    );
}

function getUri()
{
    $requestUri = $_SERVER['REQUEST_URI'];
    $scriptName = $_SERVER['SCRIPT_NAME'];

    if (dirname($scriptName) == '/') {
        $uri = $requestUri;
        return $uri;
    } else {
        $uri = str_replace(dirname($scriptName), null, $requestUri);
        return $uri;
    }
}
</pre></p>
<p>An example of the plain php classes with the business logic:<br />
<pre class="brush: php;">
namespace Demo;

class Foo
{
    public function hello()
    {
        return &quot;Hello&quot;;
    }

    public function helloName($name)
    {
        return &quot;Hello &quot; . $name;
    }

    public function getUsers()
    {
        return array('Gonzalo', 'Peter', );
    }
}
</pre></p>
<p>This class is easily testable with PHPUnit.</p>
<p>Normally I use this kind of framework to get json and jsonp. It&#8217;s pretty straightforward to get json:</p>
<blockquote><p>http://localhost/demo/foo/getUsers.json<br />
     ["Gonzalo","Peter"]</p>
<p>http://localhost/demo/foo/getUsers.jsonp</p>
<p>     cbk(["Gonzalo","Peter"]);</p></blockquote>
<p>This is a very small approach of what I have in mind, coded with a few lines to show the concept. I&#8217;m working in some more advanced features such as twig integration, security, and things like that. The idea is combine the plain PHP classes with annotations (with Addendum). Imagine a class like that:</p>
<p>Here @Render() annotation tells to the framework to use a twig template.<br />
<pre class="brush: php;">
// http://localhost/tdl/index.html

class Tdl
{
    /**
     * @Render()
     * @return array
     */
    public function index()
    {
        return array(
            'title'       =&gt; 'Simple ToDo List',
            'description' =&gt; 'Simple ToDo List',
            'author'      =&gt; 'Gonzalo',
        );
    }
}
</pre></p>
<p>And here will output a javascript file using assetic library<br />
<pre class="brush: php;">
// http://localhost/tdl/js/js.js

namespace Tdl;

use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Filter\FilterInterface;

class Js
{
    public function js()
    {
        $js = new AssetCollection(array(
            new FileAsset(MVC_PATH . '/V/Tdl/Js/nf.js'),
            new FileAsset(MVC_PATH . '/V/Tdl/Js/main.js'),
        ));

        return  $js-&gt;dump();
    }
}
</pre></p>
<p>Sometimes I think Symfony2 has all this features and developing this framework is a waste of time. Probably, but it&#8217;s cool to code it. Also it&#8217;s very easy and fast for me build prototypes. What do you think?</p>
<p>Initial commit <a href="https://github.com/gonzalo123/microFramework/tree/post1">here</a> (the code used in this post).<br />
Full code on <a href="https://github.com/gonzalo123/microFramework">github</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gonzalo123.wordpress.com/1020/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gonzalo123.wordpress.com/1020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gonzalo123.wordpress.com/1020/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.wordpress.com&amp;blog=6282145&amp;post=1020&amp;subd=gonzalo123&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gonzalo123.wordpress.com/2011/08/22/building-a-small-microframework-with-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>

		<media:content url="http://gonzalo123.files.wordpress.com/2011/08/microframework1.jpg?w=297" medium="image">
			<media:title type="html">microFramework</media:title>
		</media:content>

		<media:content url="http://gonzalo123.files.wordpress.com/2011/08/folder.png" medium="image">
			<media:title type="html">folder</media:title>
		</media:content>
	</item>
	</channel>
</rss>
