<?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>Captain_kurO</title>
	<atom:link href="http://captainkuro.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://captainkuro.com</link>
	<description>Diary of a web programmer</description>
	<lastBuildDate>Tue, 01 Nov 2011 03:55:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP Micro-Framework</title>
		<link>http://captainkuro.com/php/php-micro-framework/</link>
		<comments>http://captainkuro.com/php/php-micro-framework/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 14:56:01 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[laravel]]></category>
		<category><![CDATA[micro-framework]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=154</guid>
		<description><![CDATA[Few days ago I was searching for a RESTful PHP framework to help me develop a little project of mine. As I was searching, I stumbled upon PHP micro-framework. At first I didn&#8217;t know what that means, but as I dug deeper I saw some new ideas, new ways to develop a web application. As [...]]]></description>
			<content:encoded><![CDATA[<p>Few days ago I was searching for a RESTful PHP framework to help me develop a little project of mine. As I was searching, I stumbled upon PHP micro-framework. At first I didn&#8217;t know what that means, but as I dug deeper I saw some new ideas, new ways to develop a web application.</p>
<p>As you know, I have experienced with several PHP frameworks before, but all of them have many things in common: MVC, Controller-Action mapped to route, etc. When I read about micro-frameworks, they don&#8217;t enforce you to any fixed architecture. You could build your own architecture, they only provide the basics such as routing and database wrapper, thus the name &#8220;micro&#8221;.<br />
<span id="more-154"></span><br />
But just like PHP frameworks, there are many PHP micro-frameworks. One of the oldest is <a href="http://www.limonade-php.net/README.htm">Limonade</a>, too bad it&#8217;s not actively developed anymore, i think. The other name I stumbled upon is <a href="http://www.slimframework.com/">Slim Framework</a>, one of Sinatra-inspired framework, quite good. Then I found <a href="http://fatfree.sourceforge.net/">Fat-Free Framework</a>, which some article said &#8220;tiny script with real muscle&#8221; or what I may say &#8220;kecil kecil cabe rawit&#8221; in Indonesian.</p>
<p>A bit about Fat-Free, I like how it provides people with many &#8220;getting started&#8221; guides so new people could understand how to use it. Also, it has many features despite having such small size. I happened to read all those guides and done some &#8220;hello world&#8221; using Fat-Free. But what I dislike is how it uses PHP eval() function. I checked there are about 10 occurrences of eval(). But I&#8217;m going to keep Fat-Free as my backup choice for my project.</p>
<p>Next, I saw <a href="http://laravel.com/">Laravel</a>, a new PHP micro-framework with &#8220;Clean &amp; Classy&#8221; slogan. At first I notice how it also provides good getting started guide like Fat-Free. Even tough it has less feature, it didn&#8217;t use any eval(), so a big plus in my opinion. When I skim through Laravel source code, I realize how beautiful it is written. Laravel uses latest PHP technology like anonymous function and namespace very well. For example, let&#8217;s see a portion of Eloquent (Laravel&#8217;s ORM) class:</p>
<pre class="brush: php; title: ;">&lt;?php namespace System\DB\Eloquent;
	use System\DB;
	use System\Str;
	use System\Config;
	use System\Inflector;
	use System\Paginator;

	abstract class Model {
	...
</pre>
<p>When I saw this, I was like &#8220;This is the one!&#8221;.</p>
<p>The only downside of Laravel is that the fact it&#8217;s still new (started about June 2011) so it still need many improvements, especially its ORM. But I saw a bright future and I think I&#8217;m gonna use Laravel for my project.</p>
<p>Next? I&#8217;m gonna write a simple blog tutorial using Laravel.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/php-micro-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>I&#8217;m Back</title>
		<link>http://captainkuro.com/uncategorized/im-back/</link>
		<comments>http://captainkuro.com/uncategorized/im-back/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 14:07:58 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[random]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=148</guid>
		<description><![CDATA[I can&#8217;t believe how long has it been since I last post something here. Well I got this job that has been draining my time away from writing anything. Either that or I am just too lazy :&#124;. Anyway, now I think I have something to write about so I&#8217;ll start with writing a post [...]]]></description>
			<content:encoded><![CDATA[<p>I can&#8217;t believe how long has it been since I last post something here. Well I got this job that has been draining my time away from writing anything. Either that or I am just too lazy :|.</p>
<p>Anyway, now I think I have something to write about so I&#8217;ll start with writing a post about I&#8217;m coming back to this blog. And this is that post.</p>
<p>Next? I&#8217;m thinking about <a href="http://captainkuro.com/php/php-micro-framework/">micro-framework</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/uncategorized/im-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Block Comment</title>
		<link>http://captainkuro.com/programming/block-comment/</link>
		<comments>http://captainkuro.com/programming/block-comment/#comments</comments>
		<pubDate>Wed, 25 May 2011 10:44:49 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[block]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[comment]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=143</guid>
		<description><![CDATA[We all know what a block comment is, sometimes we use it to comment a bunch of lines of code. And sometimes we might want those lines of code to be uncommented and commented again. In a traditional way, we need to make two modifications each time, at the beginning and at the end of [...]]]></description>
			<content:encoded><![CDATA[<p>We all know what a block comment is, sometimes we use it to comment a bunch of lines of code. And sometimes we might want those lines of code to be uncommented and commented again. In a traditional way, we need to make two modifications each time, at the beginning and at the end of block comment symbol.</p>
<p>For example:</p>
<pre class="brush: php; title: ;">
usual_code();

sometimes_unused();
sometimes_unused_too();

another_code();
</pre>
<p>If we want to comment some lines:</p>
<pre class="brush: php; title: ;">
usual_code();
/*
sometimes_unused();
sometimes_unused_too();
*/
another_code();
</pre>
<p>We modified two spots. Now, I prefer to do just one modification each &#8220;toggle&#8221; (comment-uncomment switch), so I use this:</p>
<pre class="brush: php; title: ;">
usual_code();
/* Some description
*/
sometimes_unused();
sometimes_unused_too();
/**/
another_code();
</pre>
<p>To comment them:</p>
<pre class="brush: php; title: ;">
usual_code();
/* Some description
     &lt;-- only need to delete this part, one spot
sometimes_unused();
sometimes_unused_too();
/**/
another_code();
</pre>
<p>More efficient. IMHO.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/programming/block-comment/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Say No to &#8220;global&#8221;</title>
		<link>http://captainkuro.com/php/say-no-to-global/</link>
		<comments>http://captainkuro.com/php/say-no-to-global/#comments</comments>
		<pubDate>Thu, 12 May 2011 19:32:06 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[global]]></category>
		<category><![CDATA[public]]></category>
		<category><![CDATA[static]]></category>
		<category><![CDATA[variable]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=139</guid>
		<description><![CDATA[In PHP, a function (or class method) could use variables that reside in the global scope by explicitly stating them with global keyword. For example: $string = 'an apple above the head'; function break_string() { global $string; return 'break ' . $string; } This practice has some disadvantages, one of them is we can&#8217;t directly [...]]]></description>
			<content:encoded><![CDATA[<p>In PHP, a function (or class method) could use variables that reside in the global scope by explicitly stating them with global keyword. For example:</p>
<pre class="brush: php; title: ;">
$string = 'an apple above the head';

function break_string() {
  global $string;
  return 'break ' . $string;
}
</pre>
<p>This practice has some disadvantages, one of them is we can&#8217;t directly know the origin of the global variables. Let&#8217;s say we have this code:</p>
<pre class="brush: php; title: ;">
include 'common_function.php';
include 'pedicure_function.php';
include 'medicure_function.php';

function break_string() {
  global $string;
  return 'break ' . $string;
}
</pre>
<p>Can you know where is the origin of global $string? We need to look through each of those included files and search for variable $string which resides in global scope. This might take some times, so I propose a better way to utilize global variables.<span id="more-139"></span></p>
<p>Let&#8217;s create one class as a container to all global variables by using static properties. To illustrate, see this piece of code:</p>
<pre class="brush: php; title: ;">
// Global container
class G {
  public static $string;
}

G::$string = 'an apple above the head';

function break_string() {
  return 'break ' . G::$string;
}
</pre>
<p>Not only that we don&#8217;t need to write &#8220;global&#8221; in every functions, we could also find the origin of global $string easier, because it has G:: prefix. Finding the definition of a class is so much easier than finding a variable because people usually write one class per one file. Let&#8217;s take a look at this piece of code:</p>
<pre class="brush: php; title: ;">
include 'class/G.php';
include 'common_function.php';
include 'header.inc';

function break_string() {
  return 'break ' . G::$string;
}
</pre>
<p>In a glance, we could guess that G::$string originated from &#8216;class/G.php&#8217; because we know for sure that G:: means static properties of class G and usually class G (or Whatever) will be written in file G.php (or Whatever.php).</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/say-no-to-global/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple PHP Class to Generate XML Document</title>
		<link>http://captainkuro.com/php/simple-php-class-to-generate-xml-document/</link>
		<comments>http://captainkuro.com/php/simple-php-class-to-generate-xml-document/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 06:29:11 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php class]]></category>
		<category><![CDATA[simple]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=135</guid>
		<description><![CDATA[Recently I need to generate an XML document with PHP. Since it&#8217;s just a simple task of generating a form of string, I don&#8217;t use any XML parser library. So, I create this PHP class which eases me accomplishing that task. It uses PHP Magic Method to generate the XML. Let&#8217;s look at the code: [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I need to generate an XML document with PHP. Since it&#8217;s just a simple task of generating a form of string, I don&#8217;t use any XML parser library. So, I create this PHP class which eases me accomplishing that task. It uses PHP Magic Method to generate the XML.</p>
<p>Let&#8217;s look at the code:<span id="more-135"></span></p>
<pre class="brush: php; title: ;">&lt;?php
/**
 * Helps you generate XML text
 *
 * $x-&gt;div(array('id' =&gt; 'isi'), $x-&gt;span('asdf'),
 *   $x-&gt;div(
 *	   $x-&gt;span('george'),
 *	   $x-&gt;img(array('src' =&gt; 'asdf.jpg'))
 *   )
 * );
 * // Will result &lt;div id=&quot;isi&quot;&gt;&lt;span&gt;asdf&lt;/span&gt;&lt;div&gt;&lt;span&gt;george&lt;/span&gt;&lt;img src=&quot;asdf.jpg&quot; /&gt;&lt;/div&gt;&lt;/div&gt;
 */
class X {
	public function __call($name, $params) {
		$prex = '';
		if (is_array(current($params))) { // To specify tag attributes, assign those as array in first argument
			$args = array_shift($params);
			foreach ($args as $k =&gt; $v) {
				$prex .= ' ' . $k . '=&quot;' . str_replace('&quot;', '&amp;quot;', $v) . '&quot;';
			}
		}
		if (empty($params)) { // Empty tags will be shown as &lt;tag /&gt;
			return &quot;&lt;$name$prex /&gt;&quot;;
		}
		return &quot;&lt;$name$prex&gt;&quot; . implode('',$params) . &quot;&lt;/$name&gt;&quot;;
	}

	// If PHP &gt;= 5.3.0
	/*
	public function __callStatic($name, $params) {
		$prex = '';
		if (is_array(current($params))) { // To specify tag attributes, assign those as array in first argument
			$args = array_shift($params);
			foreach ($args as $k =&gt; $v) {
				$prex .= ' ' . $k . '=&quot;' . str_replace('&quot;', '&amp;quot;', $v) . '&quot;';
			}
		}
		if (empty($params)) { // Empty tags will be shown as &lt;tag /&gt;
			return &quot;&lt;$name$prex /&gt;&quot;;
		}
		return &quot;&lt;$name$prex&gt;&quot; . implode('',$params) . &quot;&lt;/$name&gt;&quot;;
	}
	*/
}

/* Example: */
$x = new X;
echo
$x-&gt;div(array('id' =&gt; 'isi'),
	$x-&gt;span('asdf'),
	$x-&gt;div(
		$x-&gt;span('george'),
		$x-&gt;img(array('src' =&gt; 'asdf.jpg'))
	)
);

/* If PHP &gt;= 5.3.0
X::div(array('id' =&gt; 'isi'),
	X::span('asdf'),
	X::div(
		X::span('george'),
		X::img(array('src' =&gt; 'asdf.jpg'))
	)
);
*/</pre>
<p>Got any question? Just ask in the comments section below.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/simple-php-class-to-generate-xml-document/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Binary Clock</title>
		<link>http://captainkuro.com/javascript/javascript-binary-clock/</link>
		<comments>http://captainkuro.com/javascript/javascript-binary-clock/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 10:08:11 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[binary clock]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=128</guid>
		<description><![CDATA[This is just some doodle I create just now. I have always wanted a binary watch (I have even seen it in an online shop), but I need to save money (too much spending already). So in the meantime, I think &#8220;Why don&#8217;t I just create one?&#8221; using code of course. So I write this [...]]]></description>
			<content:encoded><![CDATA[<p>This is just some doodle I create just now. I have always wanted a binary watch (I have even seen it in an online shop), but I need to save money (too much spending already). So in the meantime, I think &#8220;Why don&#8217;t I just create one?&#8221; using code of course. So I write this simple script:</p>
<p>Put this HTML code.</p>
<pre class="brush: xml; title: ;">
&lt;pre&gt;
	&lt;div id=&quot;full&quot;&gt;&lt;/div&gt;
	H: &lt;span id=&quot;hour&quot;&gt;&lt;/span&gt;
	M: &lt;span id=&quot;minute&quot;&gt;&lt;/span&gt;
	S: &lt;span id=&quot;second&quot;&gt;&lt;/span&gt;
&lt;/pre&gt;
</pre>
<p>And this JavaScript code in one page.</p>
<pre class="brush: jscript; title: ;">
h = document.getElementById(&quot;hour&quot;);
m = document.getElementById(&quot;minute&quot;);
s = document.getElementById(&quot;second&quot;);
f = document.getElementById(&quot;full&quot;);

function str_pad(s, n, p) {
	if (p == undefined) p = '0';
	while (s.length &lt; n) {
		s = p + s;
	}
	return s;
}

function int_to_bin(i) {
	var b = '';
	i = parseInt(i);
	while (i &gt; 0) {
		b = (i % 2) + b;
		i = parseInt(i / 2);
	}
	return b;
}

setInterval(function() {
	var d = new Date;
	h.innerHTML = str_pad(int_to_bin(d.getHours()), 6);
	m.innerHTML = str_pad(int_to_bin(d.getMinutes()), 6);
	s.innerHTML = str_pad(int_to_bin(d.getSeconds()), 6);
	f.innerHTML = d.getHours() + &quot;:&quot; + d.getMinutes() + &quot;:&quot; + d.getSeconds();
}, 1000);
</pre>
<p style="text-align: left;">And you will see something like this.<a href="http://captainkuro.com/wp-content/uploads/2011/03/binclock.jpg"><img class="size-full wp-image-131 aligncenter" title="binclock" src="http://captainkuro.com/wp-content/uploads/2011/03/binclock.jpg" alt="" width="99" height="94" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/javascript/javascript-binary-clock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>View the Current Page&#8217;s Current Source Code</title>
		<link>http://captainkuro.com/javascript/view-the-current-pages-current-source-code/</link>
		<comments>http://captainkuro.com/javascript/view-the-current-pages-current-source-code/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 04:22:33 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[current source]]></category>
		<category><![CDATA[javascript script]]></category>
		<category><![CDATA[kaskus]]></category>
		<category><![CDATA[view source]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=112</guid>
		<description><![CDATA[Do you know that when you choose to &#8220;View Source&#8221; in your browser (Ctrl+U in Firefox). You will see the page source as it is delivered by the server. Any change made by the client-side script will not be seen. So, how do we see the current page CURRENT source code? I have been using [...]]]></description>
			<content:encoded><![CDATA[<p>Do you know that when you choose to &#8220;View Source&#8221; in your browser (Ctrl+U in Firefox). You will see the page source as it is delivered by the server. Any change made by the client-side script will not be seen. So, how do we see the current page CURRENT source code? I have been using Firebug for this, but just now I see somebody post the JavaScript code for this in <a href="http://www.kaskus.us/showthread.php?t=4246019" target="_blank" >kaskus (Largest Indonesian Community)</a>.</p>
<p>Here is the code he use:</p>
<pre class="brush: jscript; title: ;">javascript:h=document.getElementsByTagName('html')[0].innerHTML;function%20disp(h){h=h.replace(/&lt;/g,'\n&amp;lt;');h=h.replace(/&gt;/g,'&amp;gt;');document.getElementsByTagName('body')[0].innerHTML='&lt;pre&gt;&amp;lt;html&amp;gt;'+h.replace(/(\n|\r)+/g,'\n')+'&amp;lt;/html&amp;gt;&lt;/pre&gt;';}void(disp(h));</pre>
<p>At a quick glance, this script will replace all &#8220;&lt;&#8221; with &#8220;&amp;lt;&#8221; and all &#8220;&gt;&#8221; with &#8220;&amp;gt;&#8221; inside the &#8220;&lt;html&gt;&#8221; tag thus removing all tags and make those tags readable.</p>
<p>Let&#8217;s break down the code:<span id="more-112"></span></p>
<ol>
<li>Retrieve a copy of the page HTML
<pre class="brush: jscript; title: ;">h=document.getElementsByTagName('html')[0].innerHTML;</pre>
</li>
<li>Define a function to make all tags readable
<pre class="brush: jscript; title: ;">function%20disp(h){h=h.replace(/&amp;lt;/g,'\n&amp;amp;lt;');h=h.replace(/&amp;gt;/g,'&amp;amp;gt;');document.getElementsByTagName('body')[0].innerHTML='&amp;lt;pre&amp;gt;&amp;amp;lt;html&amp;amp;gt;'+h.replace(/(\n|\r)+/g,'\n')+'&amp;amp;lt;/html&amp;amp;gt;&amp;lt;/pre&amp;gt;';}</pre>
<pre class="brush: jscript; title: ;">function disp(h) {
	h = h.replace(/&lt;/g,'\n&amp;lt;');
	h = h.replace(/&gt;/g,'&amp;gt;');
	document.getElementsByTagName('body')[0].innerHTML=
		'&lt;pre&gt;&amp;lt;html&amp;gt;' +
		h.replace(/(\n|\r)+/g,'\n') +
		'&amp;lt;/html&amp;gt;&lt;/pre&gt;';
}</pre>
<p>		This is the main key of the script. First it will replace all &#8220;&lt;&#8221; character<br />
		into &#8220;&amp;lt;&#8221; and all &#8220;&gt;&#8221; into &#8220;&amp;gt;&#8221;. After that, it will replace the content<br />
		of &#8220;&lt;body&gt;&#8221; into this replaced text.
	</li>
<li>Run that function
<pre class="brush: jscript; title: ;">void(disp(h));</pre>
</li>
</ol>
<p>Wanna see it in action? Open any page and type this code in the address bar. Voila.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/javascript/view-the-current-pages-current-source-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Very Simple URL Shortener</title>
		<link>http://captainkuro.com/php/very-simple-url-shortener/</link>
		<comments>http://captainkuro.com/php/very-simple-url-shortener/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 10:44:30 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[bit.ly]]></category>
		<category><![CDATA[simple]]></category>
		<category><![CDATA[simple script]]></category>
		<category><![CDATA[url shortener]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=108</guid>
		<description><![CDATA[This past few days I have seen a trend of shorting URL in (me &#038; my friend)&#8217;s Plurk. Then it struck me, why don&#8217;t we create our owns? I have seen many URL shortener website, like u.nu, bit.ly, adf.ly, de.tk, kom.ps, tinyurl.com, etcetcetc&#8230; And I also have seen some PHP source code to create one [...]]]></description>
			<content:encoded><![CDATA[<p>This past few days I have seen a trend of shorting URL in (me &#038; my friend)&#8217;s Plurk. Then it struck me, why don&#8217;t we create our owns? I have seen many URL shortener website, like u.nu, bit.ly, adf.ly, de.tk, kom.ps, tinyurl.com, etcetcetc&#8230; And I also have seen some PHP source code to create one of these. Well, just out of curiosity I want to create one from scratch.</p>
<p>So what do we need? A storage for all URLs and their keys. Since this is just a simple URL shortener (input: 1 URL, output: 1 short URL), I use just one table:</p>
<pre class="brush: sql; title: ;">CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `key` varchar(100) NOT NULL,
  `url` text NOT NULL,
  `visit` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `key` (`key`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;</pre>
<p>&#8216;id&#8217; column is the primary key, &#8216;key&#8217; column is the unique identifier of URL much like &#8220;dGouHS&#8221; in http://bit.ly/dGouHS, &#8216;url&#8217; column is the originial URL, and &#8216;visit&#8217; column simply stores how many times the short URL visited.</p>
<p>How does the app works? To keep it simple, I break down the app into many functions so that the &#8220;main program&#8221; is readable, like this:</p>
<pre class="brush: php; title: ;">// The &quot;main program&quot;, the code literally explains itself
startup();
if (is_requesting_url()) {
	if (is_key_exist()) {
		redirect_to_url();
	} else {
		display_page_with_error();
	}
} else if (is_submitting_url()) {
	if (is_url_valid()) {
		display_page_with_result();
	} else {
		display_page_with_error();
	}
} else {
	display_page();
}
shutdown();</pre>
<p><span id="more-108"></span><br />
Since all of the functions use no arguments, how could they communicate? Global variables? Since I don&#8217;t really like writing &#8220;global $something&#8221; in every function, I use a class which only consists of public static variables as &#8220;global variables&#8221;:</p>
<pre class="brush: php; title: ;">// Global &quot;variables&quot; connecting all functions
class G {
	public static $full   = 'http://localhost/short.php/'; // CHANGEME
	public static $base   = '/short.php/'; // CHANGEME
	public static $conn   = null; // Database connection
	public static $row    = null; // Last row retrieved
	public static $key    = null; // Key being requested or generated
	public static $url    = null; // URL being submitted or retrieved
	public static $error  = null; // Error message
	public static $result = null; // Result message
}</pre>
<p>This way I need only type &#8220;echo G::$full&#8221; instead of &#8220;global $full; echo $full&#8221;. Instead of putting the entire source code here, I will only explain the concept behind what each function does and you can grab the entire source code at the end of this post (yeah, skip all the way down if you want).</p>
<p>There are 3 actions possible in this app:</p>
<ol>
<li>Visitor requests a URL to a key</li>
<li>Visitor submits a URL to be shortened</li>
<li>Visitor sees the homepage</li>
</ol>
<p>And here&#8217;s the explanation for each function:</p>
<dl>
<dt>void <strong>startup()</strong></dt>
<dd>System initialization, simply connecting to database</dd>
<dt>void <strong>shutdown()</strong></dt>
<dd>Terminate the database connection</dd>
<dt>bool <strong>is_requesting_url()</strong></dt>
<dd>Check whether this is the first action.<br />
	If $_SERVER['REQUEST_URI'] contains a key then yes it is.<br />
	Assign value to G::$key.</dd>
<dt>bool <strong>is_submitting_url()</strong></dt>
<dd>Check whether this is the second action.<br />
	If $_POST['url'] is defined then yes it is.<br />
	Assign value to G::$url.</dd>
<dt>bool <strong>is_key_exists()</strong></dt>
<dd>Is the requested key exists in the database?<br />
	Try to fetch <strong>SELECT * WHERE key=G::$key</strong>.<br />
	Assign value to G::$row and G::$url.</dd>
<dt>void <strong>redirect_to_url()</strong></dt>
<dd>Send a redirection header.<br />
	Don&#8217;t forget to increase the &#8216;visit&#8217; value of G::$row.</dd>
<dt>bool <strong>is_url_valid()</strong></dt>
<dd>Check whether G::$url is a valid URL.<br />
	You could define &#8220;valid&#8221; here.<br />
	Also, insert a new entry if it is valid.<br />
	&#8216;key&#8217; column value is generated with <strong>base_convert($id, 10, 37)</strong>.</dd>
<dt>void <strong>display_page()</strong></dt>
<dd>Simply display the HTML of this app.<br />
	The HTML consist mainly of one form to submit new URL.</dd>
<dt>void <strong>display_page_with_result()</strong></dt>
<dd>Generate a result message and then display the HTML.</dd>
<dt>void <strong>display_page_with_error()</strong></dt>
<dd>Generate an error message and then display the HTML.</dd>
</dl>
<p>You know what? I realize that this kind of concept (many functions, communicating through a set of global variables) reminds me of Class and Object in OO. So, I write a variant of this app in OO style, teaser:</p>
<pre class="brush: php; title: ;">class Short {
	private $full   = 'http://localhost/my_lib/short.class.php/'; // CHANGEME
	private $base   = '/my_lib/short.class.php/'; // CHANGEME
	private $conn   = null; // Database connection
	private $row    = null; // Last row retrieved
	private $key    = null; // Key being requested or generated
	private $url    = null; // URL being submitted or retrieved
	private $error  = null; // Error message
	private $result = null; // Result message

	// The main program is broken down to these functions

	public function startup() {
</pre>
<p>All &#8220;G::$&#8221; replaced with &#8220;$this->&#8221; and all function calls get prefixed with &#8220;$this->&#8221;.<br />
Finally, <a href="http://www.ziddu.com/download/13897818/simple-shortener.zip.html" target="_blank">the complete source</a>. And a <a href="http://shr.totalh.com" target="_blank">live demo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/very-simple-url-shortener/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enums in PHP?</title>
		<link>http://captainkuro.com/php/enums-in-php/</link>
		<comments>http://captainkuro.com/php/enums-in-php/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 05:17:46 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[enum]]></category>
		<category><![CDATA[enum implementation]]></category>
		<category><![CDATA[enum in php]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=93</guid>
		<description><![CDATA[For those of you who have known PHP and programming in general, you might have noticed that PHP has no Enum. Some people say that they need Enum so they have invented several ways to emulate Enum behavior in PHP. (The list below) The plain old const from http://stackoverflow.com/questions/254514/php-and-enums/254543#254543 class DaysOfWeek { const Sunday = [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who have known PHP and programming in general, you might have noticed that PHP has no Enum. Some people say that they need Enum so they have invented several ways to emulate Enum behavior in PHP. (The list below)<span id="more-93"></span></p>
<ol>
<li><strong>The plain old const</strong><br />
from <a href="http://stackoverflow.com/questions/254514/php-and-enums/254543#254543">http://stackoverflow.com/questions/254514/php-and-enums/254543#254543</a></p>
<pre class="brush: php; title: ;">class DaysOfWeek
{
	const Sunday = 0;
	const Monday = 1;
	// etc.
}
var $today = DaysOfWeek::Sunday;
</pre>
</li>
<li><strong>Using method as Enum</strong><br />
from <a href="http://blog.agilephp.com/2008/05/11/i-want-enums-in-php/">http://blog.agilephp.com/2008/05/11/i-want-enums-in-php/</a></p>
<pre class="brush: php; title: ;">class MyProject_Authorization_RBAC_Role...
	public function REGULAR { return self::REGULAR }
	public function WEBMASTER { return self::WEBMASTER }
	public function ADMINISTRATOR { return self::ADMINISTRATOR }
</pre>
</li>
<li><strong>Create a function to do the Enum</strong><br />
from <a href="http://stackoverflow.com/questions/3836385/does-php-have-structs-or-enums/3849974#3849974">http://stackoverflow.com/questions/3836385/does-php-have-structs-or-enums/3849974#3849974</a></p>
<pre class="brush: php; title: ;">    # enum
    # Params:
    # $array MUST be of type &quot;array&quot; and MUST be passed
    # $asBitwise MUST be of type &quot;boolean&quot; and OPTIONAL passage
    #
    function enum($array, $asBitwise = FALSE) {

        if($array === null)             return FALSE;   # Error incorrect type
        if(!is_array($array))           return FALSE;   # Error incorrect type

        $count = 0; # Counter variable

        # The foreach: &amp; endforeach is just a style of programming
        # You can use brackets {} all the same
        # The case is the same for the if statements
        # I just find the colons to look a bit cleaner and so it does not
        # get confused with my javascript

        foreach($array as $i):
            if($i === null):
                if($count == 0)      define($i, 0);
                else                define($i, ($asBitwise === true) ? 1 &lt;&lt; ($count - 1) : $count);
            endif;
            $count++;
        endforeach;
    }
</pre>
</li>
<li><strong>Using inheritance as Enum</strong><br />
from <a href="http://www.jeremyjohnstone.com/blog/2008-10-05-enums-in-php.html">http://www.jeremyjohnstone.com/blog/2008-10-05-enums-in-php.html</a></p>
<pre class="brush: php; title: ;">abstract class DNSRecordType extends Enum {}

class A extends DNSRecordType {}
class CNAME extends DNSRecordType {}
class MX extends DNSRecordType {}

function printDnsRecord(DNSRecordType $type, ...) {
	   // We can now be sure $type is a DNSRecordType
}
</pre>
</li>
<li><strong>Using Interface as Enum</strong><br />
from <a href="http://forums.devarticles.com/showpost.php?p=267640&amp;postcount=7">http://forums.devarticles.com/showpost.php?p=267640&amp;postcount=7</a></p>
<pre class="brush: php; title: ;">Interface IEnum
{
	function __constructor($_value = &quot;&quot;)

	public function Value( )
	public function Set($_value)
}

Class Shape implements IEnum
{
	private $m_value;

	function __constructor($_value = &quot;&quot;)
	{
		if ($_value != &quot;&quot;)
		{
			$this-&gt;Set($_value);
		}
	}    

	public function Value()
	{
		return $this-&gt;m_value;
	}

	public function Set($_value)
	{
		switch($_value)
		{
			case &quot;Square&quot;:
			case &quot;Circle&quot;:
			case &quot;Triangle&quot;:
			case &quot;Rectangle&quot;:
			$this-&gt;m_value = $_value;
			break;
			default:
			throw new Exception(&quot;Enumeration Error, Set value (&quot; . $_value . &quot;) is not an option for this Enumeration&quot;);
		}
	}
}
</pre>
</li>
<li><strong>Even implement an Enum class</strong><br />
from <a href="http://www.phpclasses.org/package/4169-PHP-Implement-enumerated-types-using-arrays.html">http://www.phpclasses.org/package/4169-PHP-Implement-enumerated-types-using-arrays.html</a></p>
<pre class="brush: php; title: ;">class SimpleEnum{

	var $aList;

	function SimpleEnum($aItems){
		if(is_array($aItems)){
			$this-&gt;aList = array_flip($aItems);
		}else{
			die('Only allow array to construct SimpleEnum.');
		}
	}

	//Return the value of specific enum
	function is($item){
		if(array_key_exists($item, $this-&gt;aList)){
			return $this-&gt;aList[$item];
		}else{
			/*
				Using 'die' because I would like to have programmer's attention
				on referring a wrong item.
			*/
			die('No such item in SimpleEnum: '.$item);
		}
	}

	//Return the total length of enum
	function length(){
		return count($this-&gt;aList);
	}

	//Return all the enum array values
	function values(){
		return $this-&gt;aList;
	}

	//Print all enum array values
	function printValues(){
		print '&lt;pre&gt;';print_r($this-&gt;aList); print '&lt;/pre&gt;';
	}

}</pre>
</li>
</ol>
<p>But, why don&#8217;t we think about this. PHP has been around for more than 10 years and it has been without Enum since the beginning. Why do you think the PHP developers doesn&#8217;t implement Enum natively until now? Perhaps because PHP doesn&#8217;t need Enum at all. If PHP doesn&#8217;t need Enum, what would we use instead? Several forums and I myself suggest we use associative array instead. Or use the class const like the first technique. Of course there are some limitations to using associative array as Enum compared to native Enum (for example in C). In a traditional Enum, we could do these.</p>
<ol>
<li><strong>Define a custom data type consists of limited possible values and keys to each values</strong><br />
Yeah, in PHP you can&#8217;t define a custom data type, PHP is loosely typed anyway. But you can think of the associative array as the Enum, its keys as Enum keys and its values as Enum values.</li>
<li><strong>Provide an abstraction so programmers only need to think about what the value MEANS rather than the exact VALUE of the value</strong><br />
This is the real benefit of using Enum. Because it&#8217;s easier to remember &#8220;green&#8221; rather than &#8220;0x00FF00&#8243; or &#8220;pi&#8221; rather than &#8220;3.1415926&#8243;. In C, usually Enum has string names which refer to integer value. So we associate the MEANING with a STRING and represent the VALUE as INTEGER. Well, we already associate STRING to ANY TYPE of value by using associative array right?</li>
</ol>
<p>Is there any downside? Of course, one of it is because we store an associative array in a variable, anybody could change the content (aha!). If only constant in PHP could receive an array, we could do something like this:</p>
<pre class="brush: php; title: ;">class Enum {
	const Day = array('Sunday' =&gt; 1, 'Monday' =&gt; 2, 'Tuesday' =&gt; 3, 'Wednesday' =&gt; 4, 'Thursday' =&gt; 5, 'Friday' =&gt; 6, 'Saturday' =&gt; 7);
	const Number = array('Zero' =&gt; 0, 'One' =&gt; 1, 'Two' =&gt; 2, 'Three' =&gt; 3, 'Four' =&gt; 4, 'Five' =&gt; 5, 'Six' =&gt; 6, 'Seven' =&gt; 7, 'Eight' =&gt; 8, 'Nine' =&gt; 9);
}
echo Enum::Day['Sunday'];
</pre>
<p>But we can&#8217;t. So it&#8217;s up to the programmer to keep some kind of convention not to change the $enum.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/enums-in-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP: Advanced Switch Statement</title>
		<link>http://captainkuro.com/php/php-advanced-switch-statement/</link>
		<comments>http://captainkuro.com/php/php-advanced-switch-statement/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 10:25:24 +0000</pubDate>
		<dc:creator>root</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[if then]]></category>
		<category><![CDATA[switch]]></category>
		<category><![CDATA[switch statement]]></category>

		<guid isPermaLink="false">http://captainkuro.com/?p=86</guid>
		<description><![CDATA[We all know what is a switch statement. Usually we use switch to compare a variable to a set of possible value and determine what action to take if the variable has that value. For example, supposed we have this code: if ($i == 0) { echo 'Zero'; } else if ($i == 1) { [...]]]></description>
			<content:encoded><![CDATA[<p>We all know what is a switch statement. Usually we use switch to compare a variable to a set of possible value and determine what action to take if the variable has that value.<br />
For example, supposed we have this code:</p>
<pre class="brush: php; title: ;">if ($i == 0) {
  echo 'Zero';
} else if ($i == 1) {
  echo 'One';
} else {
  echo 'Does...not...compute...';
}</pre>
<p>We can transform the above code using switch statement and still keep the same purpose:</p>
<pre class="brush: php; title: ;">switch ($i) {
  case 0:
    echo 'Zero';
    break;
  case 1:
    echo 'One';
    break;
  default:
    echo 'Does...not...compute...';
}</pre>
<p>For a long time I thought that this is the limit of switch statement, comparing a variable to a set of finite values. I thought that switch cannot replace if-then-else when it involves some kind of range.<br />
For example, supposed we have this code:<span id="more-86"></span></p>
<pre class="brush: php; title: ;">if ($i &gt; 100) {
  echo 'Good';
} else if ($i &gt; 50) {
  echo 'So-so';
} else {
  echo 'Bad';
}</pre>
<p>Can the above code be rewritten using switch statement? Until yesterday I thought it can&#8217;t.<br />
But just now I see this technique:</p>
<pre class="brush: php; title: ;">switch (true) {
  case ($i &gt; 100):
    echo 'Good';
    break;
  case ($i &gt; 50):
    echo 'So-so';
    break;
  default:
    echo 'Bad';
}</pre>
<p>Brilliant, isn&#8217;t it!? I found this technique while I did some code-window-shopping. This technique utilize the PHP switch capability of using any data type.</p>
]]></content:encoded>
			<wfw:commentRss>http://captainkuro.com/php/php-advanced-switch-statement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

