<?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>Just a Few Lines &#187; coding</title>
	<atom:link href="http://justafewlines.com/tag/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://justafewlines.com</link>
	<description>That&#039;s all it takes, usually...</description>
	<lastBuildDate>Tue, 24 May 2011 21:08:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Making use of PHP closures</title>
		<link>http://justafewlines.com/2009/10/making-use-of-php-closures/</link>
		<comments>http://justafewlines.com/2009/10/making-use-of-php-closures/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 01:17:33 +0000</pubDate>
		<dc:creator>Pawel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://justafewlines.com/?p=189</guid>
		<description><![CDATA[Even though closures in PHP are not quite as easy to use as in other languages, we can still employ them for something useful. There are couple things we can call in PHP: functions, methods and static methods. Version 5.3 introduced another two callables: closures and objects implementing __invoke() method. In the previous post we [...]]]></description>
			<content:encoded><![CDATA[<p>Even though closures in PHP are not quite as easy to use as in other languages, we can still employ them for something useful.<br />
<span id="more-189"></span></p>
<p>There are couple things we can call in PHP: functions, methods and static methods. Version 5.3 introduced another two callables: closures and objects implementing <code>__invoke()</code> method.</p>
<p>In the <a href="http://justafewlines.com/2009/10/whats-wrong-with-php-closures/">previous post</a> we used closures to implement Groovy-like array utilities. Today we&#8217;ll see how closures can be used to simplify function calls and how they (don&#8217;t?) fit into class-related constructs.</p>
<h3>Unified calling convention</h3>
<p>Depending on the function type, we use different syntax to invoke it. Let&#8217;s start with an example:</p>
<pre class="brush: php">function regular_function($a1)
{
	echo __FUNCTION__  . "($a1)\n";
}

class SomeClass
{
	function regular_method($a1)
	{
		echo __METHOD__  . "($a1)\n";
	}

	static function static_method($a1)
	{
		echo __METHOD__  . "($a1)\n";
	}
}

$obj = new SomeClass;</pre>
<p>To call these functions, we say:</p>
<pre class="brush: php">regular_function(1);
$obj-&gt;regular_method(2);
MyClass::static_method(3);</pre>
<p>This is basic stuff. But what if we don&#8217;t want to hard-code the function names? For instance, what if we want to switch <code>static_method</code> with <code>dummy_method</code> for testing purposes? One option is to use <code>call_user_func_array</code> function. But then we still need to check what are we calling (function, method or static method) and invoke <code>call_user_func_array</code> accordingly.</p>
<p>Another solution is to wrap the thing we want to call in a closure. Then we get this:</p>
<pre class="brush: php">$c1 = to_closure('regular_function');
$c2 = to_closure('regular_method', $obj);
$c3 = to_closure('static_method', 'MyClass');

// same call syntax for all functions
$c1(1);
$c2(2);
$c3(3);</pre>
<p>There is absolutely no difference between calling various types of functions. We can easily pass wrapped functions as parameters (for example, in a configuration file).</p>
<p>How do we implement <code>to_closure</code> function? It&#8217;s actually a simple <code>call_user_func_array</code> wrapper:</p>
<pre class="brush: php">function to_closure($func_name, $class_or_object = null)
{
	$f = $class_or_object
		? array($class_or_object, $func_name)
		: $func_name;

	return function() use ($f) {
			return call_user_func_array($f, func_get_args());
		};
}</pre>
<p>First we determine if given function is a method or a simple function. Then we just use created callable variable <code>$f</code> in the returned closure.</p>
<p>How is this useful? Think about it this way. Without closures, to achieve the same functionality, you&#8217;d probably wrap your function calls in classes. Perhaps three separate classes &#8211; for functions, for methods and for static methods. That&#8217;s certainly doable, but requires more code. So as usually, it&#8217;s all about simplicity (followed by ease of maintainability and modification). </p>
<p>Everywhere we&#8217;d use objects to wrap functions (even handling, factories, all kinds of callbacks etc.), we can use closures. How about using closures with classes?</p>
<h3>JavaScript style functions? You wish!</h3>
<p>This section shows how to use PHP closures in JavaScript way. If you know Ruby, Groovy, Scala or any other language with well implemented closures support, the code below will probably make you smile ;)</p>
<p>Let&#8217;s extend our class from the beginning of the article with the following method:</p>
<pre class="brush: php">
// a class member to be used in closures
var $x = 'this is SomeClass:$x';

public function member_closure_test() {
	// 1) alias $this so it can be accessed in closures
	$self = $this;

	// 2) JavaScript style
	$this-&gt;js1 = function() use ($self) {
		echo "JS simple $self-&gt;x\n";
	};
	// $this-&gt;js1() yields an error
	$f = $this-&gt;js1;
	$f();

	// 3) JavaScript style with the array wrapper trick
	$this-&gt;js2[0] = function() use ($self) {
		echo "JS with array $self-&gt;x\n";
	};
	$this-&gt;js2[0](); // For some reason, this works...
}</pre>
<p>There are couple things to notice here:</p>
<ol>
<li>We alias <code>$this</code> reference with local variable <code>$self</code>. That&#8217;s because we can&#8217;t use <code>$this</code> in <code>use()</code> declaration of a closure.</li>
<li>First attempt to create a JavaScript style function. We need to dereference the closure before calling it.</li>
<li>No temporary variables here. Undeclared arrays to the rescue!</li>
</ol>
<p>Point 3) is the simplest solution I&#8217;ve come up with. As you can see, even with the array wrapper trick, we still need a temporary variable aliasing <code>$this</code>.</p>
<h3>In conclusion</h3>
<p><a href="http://wiki.php.net/rfc/closures">PHP wiki site</a> considers using closures for extending classes a &#8220;common misconception&#8221;.<br />
In other words, the &#8220;involved&#8221; syntax is not a bug &#8211; it&#8217;s a feature. Oh well, I don&#8217;t want to turn this blog into one big rant, so I&#8217;ll leave it at that ;)</p>
<p>On a positive note, closures provide new, more concise way to wrap function calls, which should reduce the number of objects floating around. They can also be used anywhere we&#8217;d use <code>create_function</code> before. And that&#8217;s definitely a good thing.</p>
<p><a href="http://justafewlines.com/wp-content/uploads/2009/10/call-wrapper.rar">Source code</a> for the article includes all presented examples.</p>
<p><script type="text/javascript">var dzone_url = 'http://justafewlines.com/2009/10/making-use-of-php-closures/';</script><br />
<script type="text/javascript">var dzone_style = '2';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://justafewlines.com/2009/10/making-use-of-php-closures/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Groovy&#8217;s ?. operator in PHP. Sort of.</title>
		<link>http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/</link>
		<comments>http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 22:31:29 +0000</pubDate>
		<dc:creator>Pawel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://justafewlines.com/?p=174</guid>
		<description><![CDATA[In almost all languages, chaining method calls on nested objects is either ugly or unsafe. Groovy found an elegant way around it with ?. operator. PHP didn&#8217;t. This article shows what can we do about it. So what&#8217;s the problem? Say you select personal records from a database. You use left joins to connect the [...]]]></description>
			<content:encoded><![CDATA[<p>In almost all languages, chaining method calls on nested objects is either ugly or unsafe. Groovy found an elegant way around it with ?. operator. PHP didn&#8217;t. This article shows what can we do about it.<span id="more-174"></span></p>
<h3>So what&#8217;s the problem?</h3>
<p>Say you select personal records from a database. You use left joins to connect the <code>Person</code> table with the <code>Address</code> table. You transform the results and put them in your data structures.</p>
<p>Now you want to display Joe&#8217;s home phone number. In Groovy, you do this:</p>
<pre class="brush: groovy">contact_list?.get_contact("Joe")?.get_address("Home")?.phone</pre>
<p>Short and <a href="http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception">NPE</a>-proof.</p>
<p>So in PHP you&#8217;d like to do this:</p>
<pre class="brush: php">$joes_home_phone = $contact_list
	-&gt;get_contact('Joe')
	-&gt;get_address('Home')
	-&gt;phone;</pre>
<p>but because you don&#8217;t know if Joe has a home phone or if he even exists, you have to do this:</p>
<pre class="brush: php">$joes_home_phone = "no home phone";
if (($t = $contact_list-&gt;get_contact('Joe')))
	if (($t = $t-&gt;get_address('Home')))
		$joes_home_phone = $t-&gt;phone;</pre>
<p>Even though the code sample above is already shorter than a naive approach (we&#8217;ve cut some lines by using assignments inside the if conditions), it&#8217;s still obscured and tedious do write. What other options do we have?</p>
<h3>How about the ternary operator?</h3>
<p>One alternative to the code above would look like this:</p>
<pre class="brush: php">$joes_home_number =	($t = $contact_list) ?
					($t = $t-&gt;get_contact('Joe')) ?
					($t = $t-&gt;get_address('Home')) ?
					$t-&gt;phone : null : null : null;</pre>
<p>And here&#8217;s another option, using basic logical operators:</p>
<pre class="brush: php">($t = $contact_list) &amp;&amp;
($t = $t-&gt;get_contact('Joe')) &amp;&amp;
($t = $t-&gt;get_address('Home')) &amp;&amp;
($t = $t-&gt;phone) || ($t = null);
$joes_home_number = $t;</pre>
<p>It seems more concise and, and some people may find it more readable (especially the last example).</p>
<p>However, this is not what logical operators are for. Also if you&#8217;re the only programmer on your team, perhaps you could get away with this, but in a group environment this style of writing is usually banned. So that&#8217;s not the answer. What is then?</p>
<h3>Other&#8217;s ideas, of course!</h3>
<p>The solution presented below is inspired by <a href="http://www.scaladudes.com/node/25">Option class</a> from Scala language. If you don&#8217;t know Scala, don&#8217;t worry. My PHP version of the idea is really simple, and uses couple basic PHP features.</p>
<p>Here&#8217;s how to use it:</p>
<pre class="brush: php">// Function call chain
$joes_home_phone = Safe::make($contact_list)
	-&gt;get_contact('Joe')
	-&gt;get_address('Home')		// safe method call
	-&gt;phone						// safe field access
	-&gt;safe_get("no home phone");	// and dereference

// Array access chain
$joes_home_phone = Safe::make($contact_list)
	-&gt;contacts['Joe']
	-&gt;addresses['Home']			// safe array access
	-&gt;phone						// safe field access
	-&gt;safe_get("no home phone");	// and dereference</pre>
<p>We can create longer call chains without any nesting or additional parentheses. The only extra code is at the beginning and at the end of the call chain. How does it work?</p>
<p>The idea here is to wrap result of every method call in a new <code>Safe</code> class instance. Because <code>Safe</code> class overrides the magic method <code>__call()</code>, we can handle cases where the invoked method returns null and allow further chaining.</p>
<p>Accessing fields is handled in a similar fashion. Custom array access relays on <a href="http://www.php.net/manual/en/class.arrayaccess.php">ArrayAccess</a> interface implementation.</p>
<p>For another example, consider the following code:</p>
<pre class="brush: php">class C1
{
	function method1() { return null; }
}

echo Safe::make(new C1)
	-&gt;method1()				// method1 returns null, but
	-&gt;nonexisting_field		// we can still safely do this
	-&gt;not_an_array[7]		// and this
	-&gt;safe_get("not found");</pre>
<p>The code prints &#8220;not found&#8221; message.</p>
<p><code>Safe</code> class implementation is rather short, so for more explanation just go ahead and look the the <a href="http://justafewlines.com/wp-content/uploads/2009/10/safe-deref.zip">code</a>.</p>
<h3>Wrapping up</h3>
<p>Of course, this solution is not a <a href="http://en.wikipedia.org/wiki/No_free_lunch_in_search_and_optimization">free lunch</a>. As you probably guessed, the price for concise and flexible syntax is performance. Simple tests showed that it&#8217;s usually 5-8 times slower than piled-up if statements. However, often times PHP code is not a bottleneck (for example when you deal with a database) and for those cases, nicer and more concise code is worth more than a few CPU cycles.</p>
<p><a href="http://justafewlines.com/wp-content/uploads/2009/10/safe-deref.zip">Source code</a> for this article contains complete implementation of the <code>Safe</code> class and some more extensive, ready to run usage examples.</p>
<p><script type="text/javascript">var dzone_url = 'http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/';</script><br />
<script type="text/javascript">var dzone_style = '2';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://justafewlines.com/2009/10/groovys-operator-in-php-sort-of/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>What&#8217;s wrong with PHP closures?</title>
		<link>http://justafewlines.com/2009/10/whats-wrong-with-php-closures/</link>
		<comments>http://justafewlines.com/2009/10/whats-wrong-with-php-closures/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 17:13:06 +0000</pubDate>
		<dc:creator>Pawel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://justafewlines.com/?p=150</guid>
		<description><![CDATA[PHP 5.3, along with many other features, introduced closures. So now we can finally do all the cool stuff that Ruby / Groovy / Scala / any_modern_language guys can do, right? Well, we can, but we probably won&#8217;t&#8230; Here&#8217;s why. Many languages provide nice and concise way of dealing with collections. This article presents &#8220;objectified&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>PHP 5.3, along with <a href="http://php.net/releases/5_3_0.php">many other features</a>, introduced closures. So now we can finally do all the cool stuff that Ruby / Groovy / Scala / any_modern_language guys can do, right? Well, we can, but we probably won&#8217;t&#8230; Here&#8217;s why.<span id="more-150"></span></p>
<p>Many languages provide nice and concise way of dealing with collections. This article presents &#8220;objectified&#8221; arrays implementation to demonstrate usage of closures in PHP 5.3.</p>
<p>Before we begin, please keep in mind that the code used is adjusted for educational purposes &#8211; performance aspects are not covered at all.</p>
<h3>How others do it</h3>
<p>Let&#8217;s start with a simple example. For the following array:</p>
<pre class="brush: php">$nums = array(10, 20, 30, 40)</pre>
<p>The task is to find all elements greater than 15.</p>
<p>So before without closures, we&#8217;d probably write something like this:</p>
<pre class="brush: php">$res = array();
foreach ($nums as $n)
	if ($n &gt; 15)
		$res[] = $n;</pre>
<p>In languages with closures support, this could look more like this (Groovy):</p>
<pre class="brush: groovy">def res = nums.findAll { it &gt; 15 }</pre>
<p>or like this (Scala)</p>
<pre class="brush: scala">val res = nums filter (_ &gt; 15)</pre>
<p>Notice how in Groovy and Scala we get pretty one-liners, because the looping part is abstracted away. With closures, we can do similar thing in PHP:</p>
<pre class="brush: php">$res = array_filter($nums, function($v) { return $v &gt; 15; });</pre>
<p>We got almost twice as many characters with PHP as with Scala, but it&#8217;s still quite readable.</p>
<p>By the way, the PHP code above uses a lambda, not a closure, but the difference is not important right now. <a href="http://wiki.php.net/rfc/closures">This site</a> provides details on PHP closures and lambdas.</p>
<p>So far so good. Let&#8217;s consider another task: find all elements greater than 15 and multiply them by 2, and then add local variable x to each element.</p>
<p>Groovy:</p>
<pre class="brush: groovy">def x = 1
def res = nums .findAll { it &gt; 15 } .collect { it * 2 + x }</pre>
<p>Scala:</p>
<pre class="brush: scala">val x = 1
val res = nums filter (_ &gt; 15) map (_ * 2 + x)</pre>
<p>and PHP:</p>
<pre class="brush: php">$x = 1;
$res =
array_map(
	function($v) use ($x) { return $v * 2 + $x; },
	array_filter(
		$nums,
		function($v) { return $v &gt; 15; })
);</pre>
<p>Now that&#8217;s not even close to Groovy or Scala.</p>
<p>Aesthetics aside, there&#8217;s an additional problem with the code above. What if we wanted to filter array elements based on keys, and not values? Well, we can&#8217;t. At least not without some workarounds.</p>
<p>Imperative way of achieving the same thing would be as follows:</p>
<pre class="brush: php">$x = 1;
$res = array();
foreach ($nums as $n)
	if ($n &gt; 15)
		$res[] = $n * 2 + $x;</pre>
<p>Perhaps it&#8217;s a bit cleaner, but when you see a code like this, you have to stop for a moment, before you actually see it: &#8220;ohh it&#8217;s just an array transformation&#8221;. So, let&#8217;s see how we can employ some rarely used PHP features to achieve something similar to what other languages have to offer.</p>
<h3>ArrayObject &#8211; the array() wrapper</h3>
<p>PHP comes with a standard library called SPL. One of the classes it provides is <a href="http://php.net/manual/en/class.arrayobject.php">ArrayObject</a>, which basically &#8220;allows objects to work as arrays&#8221;. For example</p>
<pre class="brush: php">$res = new ArrayObject(array(10, 20, 30, 40));
foreach ($res as $v)
	echo "$v
";</pre>
<p>Since ArrayObject is a built-in class, it can be extended like any other user-defined class.</p>
<h3>Arr &#8211; wrapping the wrapper</h3>
<p>Having ArrayObject class and closures at our disposal, we can start implementing our wrapper:</p>
<pre class="brush: php">class Arr extends ArrayObject
{
	static function make($array)
	{
		return new self($array);
	}

	function map($func)
	{
		$res = new self();
		foreach ($this as $k =&gt; $v)
			$res[$k] = $func($k, $v);
		return $res;
	}

	function filter($func)
	{
		$res = new self();
		foreach ($this as $k =&gt; $v)
			if ($func($k, $v))
				$res[$k] = $v;
		return $res;
	}
}</pre>
<p>Now the PHP solution for the second task discussed earlier could be rewritten as follows:</p>
<pre class="brush: php">$res = Arr::make($nums)
	-&gt;filter(function($k, $v) { return $v &gt; 15; })
	-&gt;map(function($k, $v) { return $v * 2; });</pre>
<p>What&#8217;s the main difference here? First of all, the methods are chainable, so we don&#8217;t lose readability as we ad more filters or more complicated mapping. Also notice that the closures passed to <code>filter</code> and <code>map</code> take two parameters &#8211; key <code>$k</code> and value <code>$v</code>. This allows us to use key value in a closure, which is not possible with PHP standard <code>array_filter</code> function.</p>
<p>As a side effect we also get more consistent API. With native PHP functions, we sometimes pass the closure as a first argument, sometimes we pass the array first. Sometimes we even pass more than one array&#8230;</p>
<p><a href="http://justafewlines.com/wp-content/uploads/2009/10/closures-arr-example.zip">Source code</a> for this article contains more complete version of the <code>Arr</code> class. Other useful functions (like <code>reduce</code> or <code>walk</code>) are implemented in a similar fashion.</p>
<h3>Is it worth it?</h3>
<p>I think there is no clear answer for this question &#8211; it all depends on the context and programmer&#8217;s preferences. When I first saw the syntax for PHP closures, I got a flashback  from the old Java days, when I thought that <a href="http://www.roseindia.net/javatutorials/anonymous_innerclassestutorial.shtml">anonymous inner classes</a> could be used as closures. Well, they could, but it&#8217;s like putting a lipstick on a pig. PHP closures are not as bad, but the syntax is just plain ugly.</p>
<p>Other languages with closures support provide really nice syntax to use them. You can use regular loops in Scala as well, but why would you? Someone could say that you can use closures this way in PHP too, but why would you?</p>
<p>I&#8217;m sure closures will find their uses in the PHP world (like delayed execution or automated resource management), but IMHO replacing traditional loops and array operations is not one of them. Unless, at some point, they decide to break backwards compatibility and clean-up the syntax and API&#8230;</p>
<h3>In conclusion</h3>
<p>Like with most other language features added as an afterthought (remember Java generics? or not to look that far &#8211; PHP OOP?), it will take a while before closures gain wider attention. Meanwhile, since more and more web hosting providers introduce PHP 5.3 support and PHP 6 is on the way, it&#8217;s definitely a good idea to try out this new tool.</p>
<p>To answer the question from the beginning. If you compare this</p>
<pre class="brush: php">$res = Arr::make($nums)
	-&gt;filter(function($k, $v) { return $v &gt; 15; })
	-&gt;map(function($k, $v) { return $v * 2; });</pre>
<p>to this</p>
<pre class="brush: scala">val res = nums filter (_ &gt; 15) map (_ * 2)</pre>
<p>the answer becomes clear: it&#8217;s the syntax, that&#8217;s what&#8217;s wrong.</p>
<p>I encourage you to download the <a href="http://justafewlines.com/wp-content/uploads/2009/10/closures-arr-example.zip">source code</a> for this article, where you can find more examples of how the functional approach to looping looks like in PHP.</p>
<p><script type="text/javascript">var dzone_url = 'http://justafewlines.com/2009/10/whats-wrong-with-php-closures/';</script><br />
<script type="text/javascript">var dzone_style = '2';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://justafewlines.com/2009/10/whats-wrong-with-php-closures/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Web Application Elements: Templates</title>
		<link>http://justafewlines.com/2009/09/web-application-elements-templates/</link>
		<comments>http://justafewlines.com/2009/09/web-application-elements-templates/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 12:34:45 +0000</pubDate>
		<dc:creator>Pawel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://justafewlines.com/?p=55</guid>
		<description><![CDATA[One of the things PHP does really well is templates. Actually, every PHP file is a template. This is rather unique feature, considering other platforms, like Java, .NET or Ruby. With PHP as a platform, the language itself is usually good enough for a template solution. There is, however, one feature (provided by some template [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things PHP does really well is templates. Actually, every PHP file is a template. This is rather unique feature, considering other platforms, like Java, .NET or Ruby. With PHP as a platform, the language itself is usually good enough for a template solution.</p>
<p>There is, however, one feature (provided by some template engines), that makes managing complex sites easier.<span id="more-55"></span>This feature is usually called &#8220;layouts&#8221;. By layout I mean something like <a href="http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx">master pages</a> for ASP, <a href="http://www.opensymphony.com/sitemesh/">Sitemesh</a> for Java, or <a href="http://docs.djangoproject.com/en/dev/topics/templates/">Django templates</a> for Python.</p>
<p>This article presents a simple way to achieve similar functionality in PHP.</p>
<h3>Features</h3>
<p>The functionality we&#8217;re looking for:</p>
<ul>
<li>layout support, or template inheritance (to use Django terminology)</li>
<li>easy way to define variables containing HTML</li>
<li>default values for variables</li>
</ul>
<p>And all this in less than 50 lines of code!</p>
<h3>Implementation overview</h3>
<p>Everything is wrapped in just one, easy to use class:</p>
<ul>
<li>Create new Template instance</li>
<li>set name of the template to execute</li>
<li>execute() and print the output</li>
</ul>
<p>Full <a href="http://justafewlines.com/wp-content/uploads/2009/09/wae-templates.zip">source code</a> with examples is available for download, so I won&#8217;t paste it here. I&#8217;ll just explain some implementation details you may find interesting.</p>
<p>The <code>execute()</code> method includes the template, then checks if it defined a parent template. If so, the parent is included. If that parent also defined a parent, it is included as well, etc.</p>
<p>The only tricky part here is that the output from files included in <code>execute()</code> is buffered and stored in a special variable (called <code>$body</code>). If given template defines a parent template, that parent gets access to all variables available to the child, plus the output generated by the child &#8211; the <code>$body</code>.</p>
<p>The following piece of code explains the idea:</p>
<pre class="brush: php">// execute the main template (probably in a controller if it's MVC)
echo Template::make('template1')-&gt;execute();

// which uses...
// template1.php
&lt;?
	$this-&gt;extend('layout_main');
	$this-&gt;var_set($var1, 'template1 says hi');

// Everything returned below will be available in the
// extended template (layout_main) via $body
?&gt;
This is cool!

// which uses...
// layout_main.php
&lt;?
	$this-&gt;var_use($var1, 'default value for var1');
?&gt;
&lt;html&gt;
	&lt;body&gt;
	&lt;h1&gt;&lt;?= $var1 ?&gt;&lt;/h1&gt; // template1 says hi
	&lt;?= $body ?&gt; // This is cool!
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>echo at the top prints</p>
<pre class="brush: html">&lt;html&gt;
	&lt;body&gt;
	&lt;h1&gt;template1 says hi&lt;/h1&gt;
	This is cool!
	&lt;/body&gt;
&lt;/html&gt;</pre>
<h3>Method chaining</h3>
<p>Many Template methods return $this, so we can say:</p>
<pre class="brush: php">echo Template::make()
	-&gt;name('template_x')
	-&gt;extend('layout_y')		// default layout
	-&gt;execute();</pre>
<p>Very simple way to shorten the code.</p>
<h3>Variable setting</h3>
<p>There are two ways of setting variables for templates. First one is very simple:</p>
<pre class="brush: php">// declaration
$tpl-&gt;var_set($greeting, 'Good morning');

// usage
echo "$greeting, stranger!";</pre>
<p><code>var_set()</code> method exploits one of the weird features of PHP, explained by the following example:</p>
<pre class="brush: php">function f1($p) {}
f1($x); // Notice: Undefined variable: x

function f2(&amp;$p) {}
f2($y); // Works

// Next two lines are equivalent to the line 5
$y = null;
f2($y);</pre>
<p>The other way to define variables is a bit more involved:</p>
<pre class="brush: php">// declaration
&lt;? $this-&gt;var_begin($menu) ?&gt;
	&lt;ul&gt;
		&lt;li&gt;uno&lt;/li&gt;
		&lt;li&gt;dos&lt;/li&gt;
	&lt;/ul&gt;
&lt;? $this-&gt;var_end() ?&gt;

// usage
echo "The Spanish menu: $menu";</pre>
<p>The trick here is to store the reference to the variable passed by reference. This allows <code>var_end()</code> method to assign a value to the variable passed to <code>var_begin()</code>. For those of you with C++ background, it works like <code>Type*&#038;amp</code>; parameters in function parameters.</p>
<p>Of course, output buffering is used to grab everything between <code>var_begin()</code> and <code>var_end()</code>.</p>
<h3>Complex defaults</h3>
<p>The function <code>var_print()</code> is a little helper that lets us to do this:</p>
<pre class="brush: php">// some layout's markup...

// if the extending template didn't define custom menu,
// show the default one
&lt;? if (!$this-&gt;var_print($menu)): ?&gt;
	Default menu:
	&lt;ul&gt;
		&lt;li&gt;one&lt;/li&gt;
		&lt;li&gt;two&lt;/li&gt;
	&lt;/ul&gt;
&lt;? endif; ?&gt;

// more markup...</pre>
<p>This code simply prints the $menu variable if it&#8217;s defined. Otherwise it prints the default markup.</p>
<h3>Wrapping up</h3>
<p>Solution presented in this article is rather basic. It could be extended in many ways (with support for nested variables for example), but even this simple implementation provides enough functionality to build complex layouts.</p>
<p><a href="http://justafewlines.com/wp-content/uploads/2009/09/wae-templates.zip">Source code</a> includes the Template class and usage examples.</p>
<p>So, that&#8217;s it for the first part. In the second installment of the series we&#8217;ll create the smallest usable dependency injection container :)</p>
<p>P.S. The main idea for this blog is to keep it simple. So, even if presented code may not always be very straight forward (although it should be), at least I&#8217;ll try to keep it short. This way it will be physically impossible to create anything too complicated :)</p>
<p><script type="text/javascript">var dzone_url = 'http://justafewlines.com/2009/09/web-application-elements-templates/';</script><br />
<script type="text/javascript">var dzone_style = '2';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://justafewlines.com/2009/09/web-application-elements-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

