<?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>HTMList.com, A Web Development Blog by Synapse StudiosArticles</title>
	<atom:link href="http://www.htmlist.com/category/articles/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.htmlist.com</link>
	<description>A Web Development Blog by Synapse Studios</description>
	<lastBuildDate>Fri, 27 Aug 2010 05:14:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Extending PHP 5.3 Closures with Serialization and Reflection</title>
		<link>http://www.htmlist.com/development/extending-php-5-3-closures-with-serialization-and-reflection/</link>
		<comments>http://www.htmlist.com/development/extending-php-5-3-closures-with-serialization-and-reflection/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 22:32:57 +0000</pubDate>
		<dc:creator>Jeremy Lindblom</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[magic methods]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=551</guid>
		<description><![CDATA[Our developer examines Closures in PHP 5.3]]></description>
			<content:encoded><![CDATA[<p>PHP 5.3 has brought with it some powerful and much-needed features like <a href="http://php.net/manual/en/language.oop5.late-static-bindings.php">late static bindings</a>, <a href="http://us3.php.net/manual/en/language.namespaces.rationale.php">namespaces</a>, and closures (also referred to as anonymous functions and lambda functions). Anyone who is experienced with JavaScript or who has worked with programming languages like Scheme or Lisp should realize the value that anonymous functions can bring to PHP. The <a title="PHP Closures (Anonymous Functions)" href="http://www.php.net/manual/en/functions.anonymous.php">PHP Manual explains closures</a> like this:</p>
<blockquote><p>Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class.</p></blockquote>
<p>PHP has very few <a title="PHP predefined classes" href="http://php.net/manual/en/reserved.classes.php">predefined classes</a> that are part of the core language, so naturally I was intrigued by the Closure class. The PHP Manual has this to say about the class:</p>
<blockquote><p>The predefined final class Closure was introduced in PHP 5.3.0. It is used for internal implementation of anonymous functions. The class has a constructor forbidding the manual creation of the object (issues <code>E_RECOVERABLE_ERROR</code>) and the <code>__invoke()</code> method with the calling magic.</p></blockquote>
<p>The <a href="http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke">invoke magic method</a> is also a new feature in PHP 5.3. It is called when an object is used in the context of a function (e.g. <code>$object($parameter);</code>). Since Closure objects will be used like functions, this is a critical feature of the Closure object. The Closure class may be perfectly equipped to act like an anonymous function, but it does not provide any extra utility beyond that. A <code>var_dump()</code> of a closure will reveal the functions parameters, but there is no way to get any other information about the Closure (like the actual code of the function). Trying to serialize the Closure throws an Exception and <code>json_encode()</code> just returns an empty JSON string. To make matters worse, the Closure class is <a href="http://us.php.net/manual/en/language.oop5.final.php">final</a>, so there is no way to extend it.</p>
<p>That simply wasn&#8217;t going to cut it for me. I wanted to make my own Closure class that was at least able to do the following: <span id="more-551"></span></p>
<ol>
<li>Invoke the Closure (with <code>__invoke()</code>) just like the PHP Closure class</li>
<li>Retrieve the actual code of the Closure</li>
<li>Retrieve detailed data about the Closure&#8217;s parameters</li>
<li>Retrieve the names and values of any variables inherited from the Closure&#8217;s parent&#8217;s scope (with the <code>use</code> construct)</li>
<li>Serialize and unserialize the Closure</li>
</ol>
<p>I decided to play around with the <a href="http://php.net/manual/en/book.reflection.php">Reflection API</a> to see what kind of information I could get from the Closure. A Closure is a function, so using the <a href="http://us.php.net/manual/en/class.reflectionfunction.php">ReflectionFunction class</a> provides the same information about Closures as it does about any other functions. PHP 5.3 also added the <code>isClosure()</code> method to the ReflectionFunction (in case you weren&#8217;t convinced that reflection would be helpful). After some tinkering, it became apparent that I would be able to accomplish all of my desires. I will walk you through the construction of my &#8220;SuperClosure&#8221; class and explain how the creative use of Reflection allows us to find ways around the problems normally blocking the ability to have my desired features.</p>
<h2 id="toc-1-grant-the-ability-to-invoke-the-closure">1. Grant the ability to invoke the Closure</h2>
<p>The first goal was to create the basic SuperClosure class that both encapsulates and allows invocation of the Closure. To do this I wrote a simple class with a constructor and the magic <code>__invoke()</code> method. I also included an accessor method (getter) for the actual Closure. In the constructor I created an instance of the ReflectionFunction class and stored it as a class member that helped allow invocation of the closure with a variable number of arguments. It also helped me accomplish other things later. The following code shows the basic class upon which I will be building. The complete will be shown at the end of the article.</p>
<pre class="brush: php">class SuperClosure {

	protected $closure = NULL;
	protected $reflection = NULL;

	public function __construct($function)
	{
		if ( ! $function instanceOf Closure)
			throw new InvalidArgumentException();

		$this-&gt;closure = $function;
		$this-&gt;reflection = new ReflectionFunction($function);
	}

	public function __invoke()
	{
		$args = func_get_args();
		return $this-&gt;reflection-&gt;invokeArgs($args);
	}

	public function getClosure()
	{
		return $this-&gt;closure;
	}
}</pre>
<p>The <code>__invoke()</code> method allows the SuperClosure object to be used exactly as if it was a Closure object. I had to recreate this functionality for the SuperClosure class since I was not able to extend the Closure to begin with. In order to pass arguments through to the real Closure, I used a combination of the <a href="http://php.net/manual/en/function.func-get-args.php"><code>func_get_args()</code></a> function and the <code>invokeArgs()</code> method of ReflectionFunction to ensure that any variable number of arguments could be used. I could have also used <code>call_user_func_array()</code> function, but I prefer Reflection, and since I already had an instance of the ReflectionFunction, the <code>invokeArgs()</code> method seemed like a better choice.</p>
<h2 id="toc-2-retrieve-the-actual-code-of-the-function">2. Retrieve the actual code of the function</h2>
<p>Secondly, I added code that allowed the SuperClosure class to find and store the actual code defining the closure. This feature is actually the key to doing the serialization later and is the most complicated part of the program. To accomplish this portion of the program, I used the instance of ReflectionFunction from Step 1 and the <a href="http://php.net/manual/en/class.splfileobject.php">SplFileObject</a> class, an SPL class which provides a nice object-oriented interface for dealing with files. The <code>getFileName()</code>, <code>getStartLine()</code>, and <code>getEndLine()</code> methods of the ReflectionFunction class allowed me to retrieve all the information I needed to find the source code of the Closure function. Using the SplFileObject to open and read from the source file and in combination with some string manipulation, I was able to obtain the closure&#8217;s source code. The following code shows the protected <code>_fetchCode()</code> method used to parse the closure&#8217;s code out of its source file:</p>
<pre class="brush: php">protected function _fetchCode()
{
	// Open file and seek to the first line of the closure
	$file = new SplFileObject($this-&gt;reflection-&gt;getFileName());
	$file-&gt;seek($this-&gt;reflection-&gt;getStartLine()-1);

	// Retrieve all of the lines that contain code for the closure
	$code = &#039;&#039;;
	while ($file-&gt;key() &lt; $this-&gt;reflection-&gt;getEndLine())
	{
		$code .= $file-&gt;current();
		$file-&gt;next();
	}

	// Only keep the code defining that closure
	$begin = strpos($code, &#039;function&#039;);
	$end = strrpos($code, &#039;}&#039;);
	$code = substr($code, $begin, $end - $begin + 1);

	return $code;
}</pre>
<p>The only limitations with the current version of this function are that you cannot have multiple closures on a single line and you cannot use the word &#8220;function&#8221; anywhere besides the actual closure&#8217;s declaration.</p>
<h2 id="toc-3-retrieve-detailed-data-about-the-closures-parameters">3. Retrieve detailed data about the Closure&#8217;s parameters</h2>
<p>Retrieving information about the closure&#8217;s parameters was as simple as adding a method that simply returns the result of the <code>getParameters()</code> method the SuperClosure&#8217;s instance of ReflectionFunction. That&#8217;s all. The <code>getParameters()</code> method returns ReflectionParameter objects which have several methods for getting information about the parameters including their names, values, default values, and more.</p>
<h2 id="toc-4-retrieve-the-names-and-values-of-any-variables-inherited-from-the-closures-parents-scope">4. Retrieve the names and values of any variables inherited from the Closure&#8217;s parent&#8217;s scope</h2>
<p>One of the biggest problems I had was retrieving the names and values of the variables added to the Closure&#8217;s scope with the <code>use</code> construct. There isn&#8217;t a documented way of doing this as far as I know, but I was able to figure out a way to do it after playing around some more with the ReflectionFunction class (it is just so helpful). These variables are actually included in the results of the <code>getStaticVariables()</code> method. If the closure declares any variables with the <code>static</code> keyword, these will also be included in the results. To get around this I added the <code>_fetchUsedVariables()</code> method that uses a combination of the <code>getStaticVariables()</code> method and some string manipulation of the Closure&#8217;s code (from Step 2) to find only the variables that were inherited from the parent&#8217;s scope. The following code shows the <code>_fetchUsedVariables()</code> method:</p>
<pre class="brush: php">protected function _fetchUsedVariables()
{
	// Make sure the use construct is actually used
	$use_index = stripos($this-&gt;code, &#039;use&#039;);
	if ( ! $use_index)
		return array();

	// Get the names of the variables inside the use statement
	$begin = strpos($this-&gt;code, &#039;(&#039;, $use_index) + 1;
	$end = strpos($this-&gt;code, &#039;)&#039;, $begin);
	$vars = explode(&#039;,&#039;, substr($this-&gt;code, $begin, $end - $begin));

	// Get the static variables of the function via reflection
	$static_vars = $this-&gt;reflection-&gt;getStaticVariables();

	// Only keep the variables that appeared in both sets
	$used_vars = array();
	foreach ($vars as $var)
	{
		$var = trim($var, &#039; $&amp;amp;&#039;);
		$used_vars[$var] = $static_vars[$var];
	}

	return $used_vars;
}</pre>
<h2 id="toc-5-grant-the-ability-to-serialize-and-unserialize-the-closure">5. Grant the ability to serialize and unserialize the Closure</h2>
<p>Finally, I implemented the serialization capabilities. Since an actual closure object cannot be serialized (it gives a fatal error), I had to be creative to come up with a way to do my own serialization. The code I wrote for Step 2 and Step 4 made this possible. The <a href="http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep">sleep magic method</a> allows you to hook into the serialization process, so I used this method to prepare my SuperClosure class for serialization. In order for my class to be serialized, I needed to first stop the Closure object and the ReflectionFunction object representing the Closure from being serialized. The <code>__sleep()</code> method should return an array of the class members you are serializing, so I simply left those variables out of the list. Because I was serializing the Closure&#8217;s code and static variables, it made possible in the <code>__wakeup()</code> magic method to recreate the Closure object using the code. To do this I had to use the <code>extract()</code> function on my array of used variables to import them back into the scope. Then I performed an <code>eval()</code> operation on the Closure&#8217;s code in order to recreate the Closure. <code>eval()</code> is always a risky operation, but in this case it makes sense. If you are planning to use this code for any of your own projects, I urge you to take precautions.  The following code shows the complete SuperClosure class with the additions of the <code>__sleep(</code>) and <code>__wakeup()</code> methods.</p>
<pre class="brush: php">class SuperClosure {

	protected $closure = NULL;
	protected $reflection = NULL;
	protected $code = NULL;
	protected $used_variables = array();

	public function __construct($function)
	{
		if ( ! $function instanceOf Closure)
			throw new InvalidArgumentException();

		$this-&gt;closure = $function;
		$this-&gt;reflection = new ReflectionFunction($function);
		$this-&gt;code = $this-&gt;_fetchCode();
		$this-&gt;used_variables = $this-&gt;_fetchUsedVariables();
	}

	public function __invoke()
	{
		$args = func_get_args();
		return $this-&gt;reflection-&gt;invokeArgs($args);
	}

	public function getClosure()
	{
		return $this-&gt;closure;
	}

	protected function _fetchCode()
	{
		// Open file and seek to the first line of the closure
		$file = new SplFileObject($this-&gt;reflection-&gt;getFileName());
		$file-&gt;seek($this-&gt;reflection-&gt;getStartLine()-1);

		// Retrieve all of the lines that contain code for the closure
		$code = &#039;&#039;;
		while ($file-&gt;key() &lt; $this-&gt;reflection-&gt;getEndLine())
		{
			$code .= $file-&gt;current();
			$file-&gt;next();
		}

		// Only keep the code defining that closure
		$begin = strpos($code, &#039;function&#039;);
		$end = strrpos($code, &#039;}&#039;);
		$code = substr($code, $begin, $end - $begin + 1);

		return $code;
	}

	public function getCode()
	{
		return $this-&gt;code;
	}

	public function getParameters()
	{
		return $this-&gt;reflection-&gt;getParameters();
	}

	protected function _fetchUsedVariables()
	{
		// Make sure the use construct is actually used
		$use_index = stripos($this-&gt;code, &#039;use&#039;);
		if ( ! $use_index)
			return array();

		// Get the names of the variables inside the use statement
		$begin = strpos($this-&gt;code, &#039;(&#039;, $use_index) + 1;
		$end = strpos($this-&gt;code, &#039;)&#039;, $begin);
		$vars = explode(&#039;,&#039;, substr($this-&gt;code, $begin, $end - $begin));

		// Get the static variables of the function via reflection
		$static_vars = $this-&gt;reflection-&gt;getStaticVariables();

		// Only keep the variables that appeared in both sets
		$used_vars = array();
		foreach ($vars as $var)
		{
			$var = trim($var, &#039; $&amp;amp;&#039;);
			$used_vars[$var] = $static_vars[$var];
		}

		return $used_vars;
	}

	public function getUsedVariables()
	{
		return $this-&gt;used_variables;
	}

	public function __sleep()
	{
		return array(&#039;code&#039;, &#039;used_variables&#039;);
	}

	public function __wakeup()
	{
		extract($this-&gt;used_variables);

		eval(&#039;$_function = &#039;.$this-&gt;code.&#039;;&#039;);
		if (isset($_function) AND $_function instanceOf Closure)
		{
			$this-&gt;closure = $_function;
			$this-&gt;reflection = new ReflectionFunction($_function);
		}
		else
			throw new Exception();
	}
}</pre>
<h2 id="toc-conclusion">Conclusion</h2>
<p>With some cleverness and reflection, I was able to create the SuperClosure class and extend the Closure&#8217;s normal capabilities. Although my class does not enhance the typical use of a PHP Closure it does make it possible to serialize and transport a closure and provides an interface for examining the parameters and inherited variables. This means that we can do:</p>
<pre class="brush: php">$closure = new SuperClosure(
	function($num1, $num2) {return $num1 + $num2;}
);
$serialized_closure = serialize($closure);
$unserialized_closure = unserialize($serialized_closure);
echo $unserialized_closure(1, 5);
</pre>
<p>without worrying about errors. Also, it would technically be possible to send closures through a remote service.</p>
<p>From what I have read in the PHP Manual, this class may have to be changed in the future. The Manual states this regarding anonymous functions:</p>
<blockquote><p>Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.</p></blockquote>
<p>So according to this, future versions of PHP might implement closures differently, and my class would have to be rewritten.</p>
<p>If you would like a copy of the code from this article (and an example of its use) you can find it on <a href="http://github.com/jeremeamia/super_closure">my Github account</a>.</p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=551&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/development/extending-php-5-3-closures-with-serialization-and-reflection/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Facebook vs. Twitter Clickthroughs: More Bang For Your Buck</title>
		<link>http://www.htmlist.com/cool-stuff/facebook-vs-twitter-clickthroughs-more-bang-for-your-buck/</link>
		<comments>http://www.htmlist.com/cool-stuff/facebook-vs-twitter-clickthroughs-more-bang-for-your-buck/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 17:00:09 +0000</pubDate>
		<dc:creator>Chris Cardinal</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[analytics]]></category>
		<category><![CDATA[clickthroughs]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[Social Networking]]></category>
		<category><![CDATA[statistics]]></category>
		<category><![CDATA[threadknits]]></category>
		<category><![CDATA[threadless]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[viral]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=530</guid>
		<description><![CDATA[We look at clickthrough rates from Twitter and Facebook and see how they compare.]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-532 aligncenter" title="Facebook vs Twitter" src="http://www.htmlist.com/wordpress/wp-content/uploads/2010/01/facebook_vs_twitter.jpg" alt="Facebook vs Twitter" width="381" height="214" /></p>
<p>While managing your social networking presence on Twitter and Facebook, it can be difficult to quantify the impact of each medium. While I&#8217;m a huge fan of Twitter, traffic results from earlier today on one of my sites confirmed for me what may sound like common sense: <strong>Facebook fans drive far more traffic per-user than Twitter followers for a given promotional message.</strong></p>
<p>I&#8217;m currently running a contest in association with T-shirt company <a title="Threadless.com" href="http://clickserve.cc-dt.com/link/tplclick?lid=41000000027278770&amp;pubid=21000000000210012">Threadless</a>. (It&#8217;s called <a title="Threadknits" href="http://www.threadknits.com/">Threadknits</a>, and it&#8217;s based on knitting and crocheting their t-shirt designs into crafts.) Today, Threadless posted a message on their Facebook page and  Twitter, both with essentially the same content: an invitation to check out Threadknits. They were both posted at nearly the same time.</p>
<p>The numbers are what might surprise you. Threadless has almost 1,500,000 followers on Twitter, and &#8220;only&#8221; 102,000 fans on Facebook. With the posts made within an hour of each other, my traffic on the site shot up, with a couple thousand visitors hitting by day&#8217;s end. Here&#8217;s the breakdown of traffic driven from each:</p>
<table border="1" style="border:1px dashed #000;" width="80%" cellpadding="3">
<thead>
<tr>
<td><strong>Medium:</strong></td>
<td><strong>Fans:</strong></td>
<td><strong>Visitors:</strong></td>
<td><strong>% Audience Clickthroughs:</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Facebook</td>
<td>~102,000</td>
<td>~1,110</td>
<td><strong>~1.08%</strong></td>
</tr>
<tr>
<td>Twitter</td>
<td>~1,490,000</td>
<td>~682</td>
<td><strong>~0.04%</strong></td>
</tr>
</tbody>
</table>
<p>&nbsp;<br />
The difference is absolutely staggering. Whereas Facebook generated an approximate 1.08% clickthrough rate, Twitter&#8217;s was closer to, well, 0%. 232 visitors came from Twitter or related sites directly and 450 additional clicks landed on the home page without a referrer, which I&#8217;m chalking up to clicks from Twitter clients. (Though, to be fair, this could easily overstate Twitter&#8217;s influence.)</p>
<p>On a <a title="Threadcakes" href="http://www.threadcakes.com/">previous contest</a>, Threadless would tweet and I&#8217;d see between 1,000-2,000 clicks on their roughly 1.4 million followers, so while it may be a bit low today, I think the point stands: Even at its best, Twitter for large audiences generates clickthrough rates dramatically lower than Facebook. For 2,000 clicks, the rate at 1.4M followers stood at 0.14%. A quick look at the bit.ly stats on a few links from <a href="http://www.twitter.com/aplusk">Ashton Kutcher</a> (the #1 Twitter personality by followers) shows they typically net about 20,000-30,000 clickthroughs, on 4.3M followers, gaining a decent amount on the Threadless best-case scenario all the way up to 0.48% ~ 0.60%. (This accounts somewhat for the viral nature of Twitter as bit.ly clicks are counted for retweets as well.) Naturally, clickthrough rates will vary dramatically even amongst popular Twitter personalities for a variety of reasons. I&#8217;d like to focus more on the significant difference between the Facebook and Twitter rates I witnessed today.</p>
<p>There are likely several possible reasons for this:</p>
<ul>
<li>The audience may be slightly different—people willing to consider themselves &#8220;fans&#8221; on Facebook may be more picky with their allegiance than those willing to follow an account on Twitter.</li>
<li>The phrasing and formatting of the message were slightly different—not exactly apples-to-apples as Facebook includes the logo and a text clip from the website, but I imagine this had a negligible effect.</li>
<li>My mileage may vary—this is an admittedly small sample size, but I think the evidence and logic around these results indicate they&#8217;re not anomalous.</li>
<li>Most importantly, <strong>Facebook lingers while Twitter sails by. </strong>Users are probably more likely to follow links during their Facebook time than from a passing Twitter notification unless it&#8217;s of particular interest to them.</li>
</ul>
<p>That last point is particularly important. Facebook, having reconfigured their News Feed yet again, no longer sorts things there chronologically. They&#8217;ve merged the Highlights functionality back into the News Feed which they now use to keep certain posts &#8220;stickier&#8221; than others based on what they believe you might be interested in. (It manages to do a strikingly horrible job at this compared to how it used to perform, but that&#8217;s a conversation for a different post.)</p>
<p><strong>With Twitter, the very nature of real-time can be summed up: blink and you miss it.</strong> While you can use a Twitter client to review tweets over the past day or two, it&#8217;s still less likely your tweet was as visible over Twitter as a post would be on Facebook&#8217;s News Feed. I&#8217;d like to see some more statistics on total audience reach. The clickthrough rate surely only tells part of the story—I&#8217;d be far more interested to learn what percentage of each audience even <em>saw</em> the post, and determine true clickthrough rates from that.</p>
<p>In the end, it&#8217;s important to consider the overall spirit of the findings here. Twitter is great for growing virally and interacting with customers, but your message on Facebook may have a far more lasting impression and generate greater returns, even if fans are more of a fight to procure. Engage on both, but recognize the differences between them and leverage each of their strengths. I&#8217;ll likely post about the best way to do that for each site in the near future.</p>
<p><small><em>(The above graphic represents the total clickthrough breakdown by medium assuming a linear progression of Threadless&#8217; Facebook audience to match their Twitter audience, maintaining the same clickthrough rates from today&#8217;s traffic. It&#8217;s likely the Facebook clickthrough rate could in fact fall some as their audience grew, but it&#8217;s my belief that it would still beat Twitter, user for user.)</em></small></p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=530&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/cool-stuff/facebook-vs-twitter-clickthroughs-more-bang-for-your-buck/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Is PHP 5.3 Terminal?  Well, It&#8217;s Getting One For Namespaces</title>
		<link>http://www.htmlist.com/development/php-5-3-namespaces-backslashes-terminals-and-you-the-art-of-language-building/</link>
		<comments>http://www.htmlist.com/development/php-5-3-namespaces-backslashes-terminals-and-you-the-art-of-language-building/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 06:55:26 +0000</pubDate>
		<dc:creator>Edgar Hassler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[computer science]]></category>
		<category><![CDATA[constructs]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[terminals]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=370</guid>
		<description><![CDATA[A language lives and dies by how easy it is for a person to express something within that language. But the ease in expression is much like the type I and type II error rate in a statistical test: as you adjust one to be nearer to where you want it to be, the other [...]]]></description>
			<content:encoded><![CDATA[<p>A language lives and dies by how easy it is for a person to express something within that language.  But the ease in expression is much like the <a href="http://en.wikipedia.org/wiki/Type_I_and_type_II_errors">type I and type II error rate</a> in a statistical test:  as you adjust one to be nearer to where you want it to be, the other gets farther away.  So the architects of a language have to choose between adding more keywords and constructs or having longer, but simpler sequences of existing ones.</p>
<p>PHP is a very easy language to learn and use because it has a syntax that is a simplified sampling from C++/Java and Perl.  People who use these languages pick up PHP fast, and people who haven&#8217;t used any languages often learn PHP with as much ease as they would learn Perl.</p>
<p><span id="more-370"></span></p>
<h3 id="toc-a-bit-about-namespaces">A bit about namespaces</h3>
<p>Most languages have <a href="http://en.wikipedia.org/wiki/Namespace">namespaces</a> in one form or another. A namespace is a lot like a <a href="http://en.wikipedia.org/wiki/Class_(computer_science)">class</a>: it is a named entity that houses functions and classes, whereas a class is a named entity that houses properties and methods. Namespaces are found, in one form or another, in most popular languages. In C++ there are explicit namespaces and the <code>namespace</code> keyword.   In Java, since you are allowed to have classes nested within classes, classes act as namespaces. Namespaces make it easier to organize and call your code. If you have a bunch of classes that work together to do something you might name them in a similar way. For example, we here at the <a href="http://www.synapsestudios.com/">Studios</a> sometimes use the following classes:</p>
<blockquote><p><code>Canopy_Xml_Document<br />
Canopy_Xml_Document_CDataSection<br />
Canopy_Xml_Document_NodeList<br />
Canopy_Xml_IWritable<br />
Canopy_Xml_Exception</code></p></blockquote>
<p>With namespaces, we could define a namespace <code>Canopy</code>, add to it a namespace <code>Xml</code>, and then add classes <code>Document</code>, <code>Exception</code> and interface <code>IWritable</code>. We could also add a <code>Document</code> namespace and add classes <code>CDataSection</code> and <code>NodeList</code>. Then we could just tell PHP that we want to refer to things in a certain namespace. We would simply write:</p>
<blockquote><p><code>use Canopy::Xml;<br />
$D = new Document(); //$D is equivalent to a Canopy_Xml_Document<br />
</code></p></blockquote>
<p>In the beta builds of PHP 5.3, the terminal &#8220;::&#8221; called the <a href="http://en.wikipedia.org/wiki/Scope_resolution_operator">scope resolution operator</a> (SRO) is used to denote namespaces.  So, in the same way that one would write <code>Class::staticMethod()</code> one could write <code>NamespaceA::NamespaceB::functionInNamespace()</code>.  This is the same operator used in C++, and it is intuitive since it refines a name to a scope where that name belongs.</p>
<h3 id="toc-phps-sro-problem">PHPs SRO problem</h3>
<p>Recently, PHP has had to abandon using the SRO, forego the syntax of other languages and has had to make up their own way of denoting a namespace.  One reason for this is that bare words in PHP can have multiple meanings.  For example, in PHP you can do:</p>
<blockquote><p><code>const('A','constant');<br />
function A() { return 'function'; }<br />
class A(){  public _toString(){ return 'class'; } }<br />
</code></p></blockquote>
<p>such that</p>
<blockquote><p><code>echo A;            // constant<br />
echo A();         // function<br />
echo new A();  // class<br />
</code></p></blockquote>
<p>all do what you&#8217;d expect. But in namespaces, there&#8217;s some ambiguity introduced.  Consider rather <code>A::B::C()</code> is namespace <code>A</code>, class <code>B</code>, static method <code>C</code>, or namespace <code>A::B</code>, function <code>C</code>.  In C++ you&#8217;re not allowed to have a symbol like <code>A</code>, <code>B</code>, or <code>C</code> represent multiple types of things, so using the SRO does not arrive at ambiguity there. (Instead, you get an error.) But since PHP <em>does</em> allow for that type of thing, the internals team had to choose between:</p>
<ol>
<li>Not allowing namespaces to have functions, but rather only classes, thus raising the ire of the community.</li>
<li>Using some terrible terrible other operator to indicate namespaces, thus raising the ire of the community. (Quoth internals team member: &lt;@CelloG&gt; % is also possible but holy god almighty it is fugly</li>
<li>Put off namespaces until (or if) something decent can be figured out, thus raising the ire of the community.</li>
</ol>
<p>The team decided on 2, going with the \ character.</p>
<h3 id="toc-whats-that-mean-for-the-language">What&#8217;s that mean for the language?</h3>
<p>The <a href="http://wiki.php.net/_media/rfc/php.ns.txt?id=rfc%3Anamespaceseparator&amp;cache=cache">discussion</a> was concerned with preventing unanticipated behavior from just making a rule to disambiguate rather a function or static method is called. I feel that throwing an error (or warning and choosing one) whenever that situation arises would be a perfectly acceptable solution. I would also have been happy to see them further follow Java&#8217;s lead and allow classes to be nested. Then there is no ambiguity between a static method and a function because they are the same. This would probably require much more work and you would have to allow class definitions across multiple files, but I feel this is a better option than &#8216;\&#8217;. To that end I would have enjoyed option 1 over option 2.</p>
<p>The most cited complaints about PHP is how there is little consistency in function names and in argument order. This new &#8216;\&#8217; operator adds to the &#8220;weird-factor&#8221; which makes it more difficult for people to read and use the language. It further marginalizes PHP, adding to a series of minor but obnoxious issues proponents are embarrassed by.</p>
<p>The language is adrift with little direction, trying to address the wants of its developers, and adding a terminal is payment for a lack of planning and a general stubbornness of the internals list to consider namespaces back when the 5 changes were initially being discussed.  On one hand I feel like this has ominous portents for PHP, but on the other, I&#8217;m really happy to have namespaces. For our domain, it still doesn&#8217;t make sense to jump ship to Groovy or Python, and it would take a lot of new terminals to push us over the edge. And while it&#8217;d be nice to see PHP not give more ammo to detractors, however menial, the discussion log makes it clear what issues they were struggling with.</p>
<p>Frederik Holmström <a href="http://loveandtheft.org/2008/10/26/set-sail-for-fail-php-namespaces/">points out</a> another flaw with the backslash, as well, but many commenters note that the internals team knew there was no perfect solution here.</p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=370&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/development/php-5-3-namespaces-backslashes-terminals-and-you-the-art-of-language-building/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Project Management Tips from the Developer&#8217;s Point of View</title>
		<link>http://www.htmlist.com/development/project-management-tips-from-the-developers-point-of-view/</link>
		<comments>http://www.htmlist.com/development/project-management-tips-from-the-developers-point-of-view/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 23:48:37 +0000</pubDate>
		<dc:creator>Brandon Ching</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[management]]></category>
		<category><![CDATA[project management]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[scrum]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[task management]]></category>
		<category><![CDATA[time management]]></category>
		<category><![CDATA[waterfall]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=320</guid>
		<description><![CDATA[Brandon discusses some helpful principles of project management, from the developer's point of view.]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s post is on something a bit different but still very much relevant in the web development world: project management. Now, I&#8217;m not all that old and I haven&#8217;t been a web developer for all that long (about 6 years in total, 3 actually getting paid ;-) but I have had the opportunity of working for a medium-sized media company with a development team of about 25 developers, a small 5-6 person development company (3 developers), and as an independent contractor.</p>
<p>When I began my career at the medium sized company, I initially saw my project managers as a pain in the ass. All I was interested in doing was coding. I had my own ideas of how the project or feature was going to be done and I thought that I could handle deadlines and project requirements better than they could. Was it really necessary to ask me multiple times a day what I was doing and what percentage of the project was still left to be done? PM&#8217;s gave new meaning to the phrase &#8220;avoid like the plague.&#8221; In all honesty, I wondered why in the hell these people were even hired to begin with. I just could not see the role of a project manager as being all that important.</p>
<p><span id="more-320"></span></p>
<p>Of course, after a bit of development work and experience doing projects with and without them, I found myself having moments of&#8230; &#8220;OMFG&#8230;where is my project manager?&#8221; As developers, void of project managers, we often get carried away with the art that is code. We plan for one thing but, weeks post-deadline, end up creating something entirely different. Does it work? Usually. Is it beautiful? Maybe. Is it what was promised to the customer? Well, no.</p>
<p>I&#8217;m not just talking about instances where a simple login feature ballooned into a grand hierarchical authentication scheme. I&#8217;m also talking about those projects, that for some reason or another, we just despise working on and push off completion; sometimes even writing substandard code just to get it over with. And don&#8217;t forget those projects that are just so complex that we&#8217;re not even sure if we are starting at the right place, much less dedicated to a deadline of any sort.</p>
<p>It seems that the problem here is not one of competence—most of us could, if we really tried to, stick within initial specs and scope. To me the problem lies in the fact that without the role of the project manager on the team, we lack the time and task management designed to keep us on track. We are trained in how to solve problems of logic through good coding principals and design. We are artists. Our canvas is digital and we sometimes let our creativity and desire for compounding beauty interfere with the job we were hired to do. We are not trained in restraint; the project manager is, at least in theory.</p>
<p>Depending on your experience, I suppose this next statement may be gospel or blasphemy, but to me, it is gospel all the way. The successful completion of any project hinges upon a solid development methodology based in clearly defined project goals, block specifications, complete use cases, and the division and distribution of task level development. A good project manager will be able to take high level design specs and goals from a product manager or customer contact and break them out into clearly defined and manageable building blocks. Each block can then be broken down into feature/requirement sets which can finally be tasked out to the developer/s for completion. This is the job of the project manager, not the developer. Developers should only be given spec&#8217;d out tasks with detailed use cases and an explanation of <em>exactly </em>what should be done. It is then up to the developer to determine how the task will be done.</p>
<p>Now, this is not to say that developers are not to be involved in planning or design phases of projects; by nature, they have to be. However, design and planning meetings involving developers should be focused on the technical goals of the project or block, not on management and product/customer level concerns. These meetings must be narrow in focus and should have a clearly defined result. For instance, determining the database schema for the project or settling on a development framework. The layer of abstraction here is critical in keeping the project within scope and to prevent developers from expanding on or reducing the project deliverables. Once the meeting objectives have been met, project managers should then be able to chunk and task out the technical specs to the team of developers.</p>
<p>Now, up until a little while ago, I hated the word &#8220;task.&#8221; Every morning I would check my email and see, &#8220;You have been assigned a new task from&#8230;&#8221; after which my head would sink low and I would seriously contemplate my career path yet again. I would constantly wonder why everything had to be a task: a task to change a misspelled word, a task to add 5 pixels of spacing to the end of the page. Wouldn&#8217;t it just be easier to send me an email or IM or for goodness sake, just turn around and tell me? Surely this couldn&#8217;t be the Zen that is programming? However, recent experience has taught me that, by God, we all need tasks just like we all need competent project managers!</p>
<p>Task assignment, and by extension, a good task management system (note that a task/project management system is very different from a strict bug tracking system) is an absolute necessity for project management. Proper task etiquette enabled by a solid and complete project management system serves many purposes. First and foremost to developers, it serves as our grocery list. It tells us EXACTLY what we have to do, when it needs to be done by, and contains a history of the problem or feature (most PM system tasks have comments/histories and file attachment capabilities). From the management side of things, a PM system will track the number of hours developers spend on each task which can then be used for billing or other performance metrics. It also can serve as a yardstick in determining the level of project completion by showing a variety of statistics based on ticket assignment, time used, percentage of tasks complete for a given project, and developer performance.</p>
<p>Not to sound too preachy (or take too much of an aside), but I have come across a number of good techniques gathered from the various project managers and lead developers I have worked with in the past that I would like to share and recommend that people use.</p>
<h3 id="toc-quote-tasks">Quote Tasks</h3>
<p>Make use of quote tasks. It may take a little more time and to some it may seem really useless, but in the end it will serve as a good measure of your time estimation abilities and speak to the thoroughness of your work. The way it works is that for every task you are assigned, unless fixing the problem will take less than 10 min., in the comments section you should list the files and line numbers that you will need to make changes to in addition to a brief one liner explaining the expected change. You then assign the ticket back to your project manager to quickly review. If your time estimate falls within the allowable project time, then you will get the task back and no matter how many days or weeks may pass, you will know immediately what needs to be fixed and where.</p>
<h3 id="toc-notate-completed-tasks">Notate Completed Tasks</h3>
<p>When tasks are complete, you should list each file and line number range that you made modifications to and provide a one or two sentence description of changes (in addition your regular brief outlining the totality of changes). This makes tracking changes easier for those who may follow you and serves as a written history in a developers words of exactly what was done for the task.</p>
<h3 id="toc-the-six-hour-work-day">The Six-Hour Work Day</h3>
<p>One small tip on time management and allocation I learned from my last PM was to only allot 6 hours of estimated work in a day. He said that the remaining 2 hours are spent on bathroom breaks, water cooler conversations, task switching ramp up, nerf fights, etc. At first I thought this was strange. Could bathroom breaks really take up 2 hours of my working day? But as I was tasked on this schedule, it seemed to work out pretty well. While I didn&#8217;t exactly lose 2 hours doing random things, what did happen was that I was rarely under pressure to squeeze out tasks leaving me less stressed and able to produce better quality and more thoroughly tested code and documentation. Funny thing, comparing a &#8220;6 hour&#8221; work day with the regular, &#8220;get as much work done in the 8 hours you are here&#8221; approach, I felt more productive and competent under the 6 hour routine. Give it a try, you may be surprised.</p>
<h3 id="toc-developers-as-project-managers-warning">Developers as Project Managers: Warning</h3>
<p>Developers should never be placed in the role of a project manager; creating and managing their own tasks. However, sometimes there is little choice (little company resources, sole operation, etc). If this is the case, expect that as a developer you will be spending probably 1/4-1/3 of your day planning and managing tasks; <em>not</em> working on them. Be sure your boss knows this if they are not willing or able to task out projects properly to begin with. This is really for your sanity and for the thoroughness that comes with being a competent developer. Now, in the rare case where you as the developer are tasked with actually taking customer specs and being told to simply get it done, placing the entire development life cycle on you or your team&#8217;s shoulders, I strongly suggest that you ask management to hire a project manager. If that is not possible then maybe you should be dusting off that resume because project specing, chunking, and higher level project management duties like those are not your job. There is a good reason developers are not PM&#8217;s and PM&#8217;s are not developers.</p>
<h3 id="toc-the-devils-in-the-details">The Devil&#8217;s in the Details</h3>
<p>Nag, nag, nag. If you get assigned tasks that are too general in scope and you have any questions about exactly what it is that your PM or boss is asking for, send the ticket back and ask for further explanation. It usually only takes a few times doing this for your boss to get the idea of what information you need to get your work done right. Remember, training goes both ways; you learn from your boss as much as your boss learns from you. It&#8217;s better to take the time upfront and get accurate and detailed specs than for you to guess and have to go back and rewrite something down the road.</p>
<p>All that being said, there are a number of development methodologies out there to help you and your team develop software in an efficient and smart manner. Now, as I&#8217;ve made crystal clear, I&#8217;m not a PM so I don&#8217;t claim to be an expert on any development methodology, but I take particular affinity to <a href="http://en.wikipedia.org/wiki/Agile_software_development" target="_blank">Agile</a> development methods like <a href="http://en.wikipedia.org/wiki/SCRUM" target="_blank">Scrum</a>. Any methodology where you as a developer are protected from business processes (changes in specs/customer expectations, etc) external to your core job function is a winner in my book. Avoid the traditional <a href="http://en.wikipedia.org/wiki/Waterfall_model" target="_blank">waterfall</a> and <a href="http://en.wikipedia.org/wiki/Cowboy_coding" target="_blank">cowboy</a> coding approaches as they are highly inflexible and in the former case, plain stupid as a development methodology for any business.</p>
<p>So there! I hope I&#8217;ve been able to give a little personal experience to you developers out there (and you managers) who may be a little too code-centric. Don&#8217;t ignore the management side of your business. It can save your sanity and make you a better developer in the process!</p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=320&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/development/project-management-tips-from-the-developers-point-of-view/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>The Lazy, Clever Programmer: A Compendium Of Code Reuse &amp; Recycling</title>
		<link>http://www.htmlist.com/development/the-lazy-clever-programmer-a-compendium-of-code-reuse-and-recycling/</link>
		<comments>http://www.htmlist.com/development/the-lazy-clever-programmer-a-compendium-of-code-reuse-and-recycling/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 07:42:29 +0000</pubDate>
		<dc:creator>Edgar Hassler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code recycling]]></category>
		<category><![CDATA[code reuse]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[currying]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[libraries]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[practices]]></category>
		<category><![CDATA[programming concepts]]></category>
		<category><![CDATA[programming techniques]]></category>
		<category><![CDATA[spl]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=114</guid>
		<description><![CDATA[Edgar takes an excruciatingly detailed look at code reuse and recycling. He examines when to just say no and how to best build for reuse, along with the pitfalls and successes you'll stumble upon along the way.]]></description>
			<content:encoded><![CDATA[<p>I started getting &#8220;serious&#8221; about development because I had a desire never to write lengthy, wandering streams of code again.  It was not for any reason but unadulterated laziness—the kind that so overpowers the better senses as to force a person to spend hours in a chair with the express goal of <em>not</em> spending hours in said chair.  It&#8217;s a wild, consuming laziness that seems to know no bounds.<br id="tume" /></p>
<p id="k51g">As developers, once we start separating our code into abstract ontological typologies, we make use of the human mind&#8217;s phenomenal ability to work with types.  Our code becomes less about jump tables and registers and more about users, email messages and images.  What once was a problem of allocating resources and operations within the computer becomes an abstract, logical problem within a collection of objects.  Like children awe-struck by stories of magicians of old, speaking incantations and pressing their wishes into reality by the power of their mind alone, we become drunk with the sense of awe and possibility.</p>
<p>We *really* dive into things after the jump, so go ahead and hit it.</p>
<p><span id="more-114"></span></p>
<p>The magician&#8217;s spell is our codebase, and as they toil in their laboratories collecting newts and dragon finger-nails, so we assemble libraries or components and frameworks.  We write ever more diverse and sprawling codebases to power our behemoth, monolithic applications and we grow increasingly unhappy with the amount of time we spend writing the same code over and over.  As we come up with more magic to shorten our tasks, we outpace ourselves by envisaging larger and larger projects.</p>
<p id="v:qv2">As we write better, more reusable code, early on in this process we experience the satisfaction of leveraging our components to achieve results.  So developers (those of us who aren&#8217;t terrible) get into this groove of <em id="q3wz">reducing </em>the size of the logical elements we write, <em id="q3wz0">reusing </em>those elements, or <em id="q3wz1">recycling </em>them through extension or <a id="xgi0" title="currying" href="http://en.wikipedia.org/wiki/Currying">currying</a>. Over time, by constantly working to reuse our own code, we choose practices that work well for ourselves and discard practices that don&#8217;t work as well or slow down our workflow. For developers flying solo or those working on small projects, this evolutionary process is a sufficient way of going about things.<br id="neyv" /></p>
<p id="neyv2">But there&#8217;s trouble when we add other players into the mix—other developers, a user interface person, a database person, a sysadmin, a project mana-jerk: as a developer, they don&#8217;t have access to our &#8220;experience&#8221; of the code and we don&#8217;t have access to theirs.  So the practices, workflows and logic which made sense to us when we built a component for personal reuse may not make nearly as much sense as we&#8217;d hope to another developer who tries to work with it. Worse, we don&#8217;t learn from these mistakes because we may not even know they&#8217;ve been made.  Even if we suspect there&#8217;s trouble—perhaps a dead fish in your computer case or threatening instant messages—we still may not know enough about the mistake to be able to affect positive changes on our behavior.<br id="adm7" /></p>
<p id="v:qv3">We&#8217;ve been doing some extra work on our libraries at the Studios, and we&#8217;ve been arguing about the why and how some our many programmes for code re-use have failed, miserably so, and the surprising things that are still in use today.</p>
<h3 id="toc-recycling-aluminum-plastic-and-code" id="v:qv4">Recycling Aluminum, Plastic and Code</h3>
<p><a name="recycle"></a></p>
<p id="v:qv5">I envoked the slogan &#8220;reduce, reuse and recycle&#8221; earlier because refuse recycling serves as a good metaphor for code reuse, and frankly, because you can take the magician allegory only so far. Recycling is expensive: It has all of the costs of trash collection (save the landfill/incinerator/New Jersey <em id="nugt">[Hey!—Editor from NJ]</em>) and adds the cost of sorting and additional transportation costs. The idea is that value is recuperated from the actual recycled materials, but that&#8217;s not always the case. (See the parallel yet?) From an <a id="v:qv6" href="http://environment.about.com/od/recycling/a/benefit_vs_cost.htm" target="_blank">about.com article</a> on recycling:</p>
<blockquote id="v:qv7">
<p id="v:qv8">Michael Shapiro, director of the U.S. Environmental Protection Agency&#8217;s Office of Solid Waste, also weighed in on the benefits of recycling:</p>
<p id="v:qv9">&#8220;A well-run curbside recycling program can cost anywhere from $50 to more than $150 per ton trash collection and disposal programs, on the other hand, cost anywhere from $70 to more than $200 per ton. This demonstrates that, while there&#8217;s still room for improvements, recycling can be cost-effective.&#8221;</p>
<p id="v:qv10">But in 2002, New York City, an early municipal recycling pioneer, found that its much-lauded recycling program was losing money, so it eliminated glass and plastic recycling. According to Mayor Michael Bloomberg, the benefits of recycling plastic and glass were outweighed by the price &#8212; recycling cost twice as much as disposal. Meanwhile, low demand for the materials meant that much of it was ending up in landfills anyway, despite best intentions.</p>
</blockquote>
<p id="v:qv11">We can draw parallels between the things that drive the cost of some municipal recycling programs up past those of others and the things that reduce our ability to reuse software.</p>
<p id="z.8t1">Consider the following factors:</p>
<ul id="v:qv12">
<li id="v:qv13"> Volume of recyclables / Volume of components to reuse</li>
<li id="v:qv14"> Volume of non-recyclables /  <span id="wzps" style="background-color: #ffffff;">How many components </span>are NOT reused</li>
<li id="z.8t2">Adoption of the recycling program / Adoption of libraries and frameworks by developers (consistently high usage rates are necessary for effectiveness)</li>
<li id="v:qv15"> Choices as to what to recycle and what not to recycle / Clearly defined boundaries on which components are reusable and which ones are not</li>
<li id="v:qv16"> Time it takes to sort through the material to separate the recyclables / Developer&#8217;s ability to know what&#8217;s already done and in the library or framework, versus what they have to build, versus what they want to build just for the hell of it<br id="jwz9" /></li>
<li id="v:qv18"> Expense to transport material /  Overhead associated with libraries and frameworks and autoloaders and oh my</li>
</ul>
<p id="ywj_0">In software development as in refuse recycling, we naturally want to reuse as much as possible. But the return on recycling can vary greatly from item to item. And when you factor in the cost of setting up a component for reuse (<span id="q1cq" style="background-color: #ffffff;">introducing it into the environment, building with proper levels of flexibility and extensibility</span>) and the non-trivial, yet oft-overlooked cost of the time a developer spends familiarizing themself with the way you&#8217;ve designed the component, it may not make economic sense to recycle certain components.<br id="f7wt" /></p>
<p id="v:qv20">It&#8217;s up to the savvy developer to decide what will be recycled and what will not be recycled. Sometimes we make poor choices and have components that are stuck into frameworks that we never use. This is a double-whammy, since we spend more time building the component for reuse and designing for scenarios which will never occur. How do we minimize this and select the best candidates for reuse? Let&#8217;s get into that.<br id="iq75" /></p>
<h3 id="toc-choosing-what-to-recycle" id="v:qv23">Choosing What To Recycle</h3>
<p><a name="choosing"></a></p>
<p id="v:qv24">My alma mater, Arizona State University (ASU, go Devils!), has separate recycling bins for plastic and aluminum all around campus.  ASU doesn&#8217;t recycle <em id="r2b7">only</em> aluminum and plastic bottles, but these are the most prominent containers around campus. This decision makes a lot of sense because students go through a lot of soft drink cans and water bottles daily, while their paper waste output in public thoroughfares on campus is considerably less. (You normally sort and toss your flyers, notes or other paper propoganda once you get back to your dorm, for instance.)<br id="kv9c" /></p>
<p id="kv9c2">Arizona State makes up a significant portion of the city of Tempe.  Tempe&#8217;s residents output a larger variety of refuse so their recycling effort has tried to be more inclusive of other materials; almost something of a long-tail of recycling, to a point.<br id="d502" /></p>
<p id="v:qv25">It&#8217;s too easy to hang oneself in trying to make ever increasingly complex and elaborate artifices in the name of reuse. Deciding what components to build for reusability is an important part of making code reuse feasible. I wont enumerate the number of projects that we took extra time on so that we could reuse them only to have them languish in a corner of our code repository, never to see the light of day again. Nor will I tell you the dollar amount associated with the number. I will say that it&#8217;s significant.<br id="bx5l" /></p>
<p id="bx5l2">But worse still is the number of hours we&#8217;ve spent coding the same component over and over again, each time a new iteration for a new project, when one well-developed go at it would&#8217;ve delivered a highly reusable, stable piece of brilliant cost-savings and elegant code. (Realistically, we develop a &#8220;reusable&#8221; component each time, making it &#8220;better&#8221; each time.)<br id="bx5l3" /></p>
<p id="v:qv26">The best way to know what components are good candidates for reuse is to know from experience.  If you don&#8217;t have experience I suggest you develop a time portal to the future and observe the results of your work before doing it. My preferred type of &#8220;time portals&#8221; are books on design patterns:</p>
<p>Martin Fowler&#8217;s &#8220;<a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FEnterprise-Application-Architecture-Addison-Wesley-Signature%2Fdp%2F0321127420%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1216276144%26sr%3D1-1&amp;tag=htmlist-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Patterns of Enterprise Application Architecture</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=htmlist-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" />&#8220;, Alur et al&#8217;s &#8220;<a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FCore-J2EE-Patterns-Practices-Strategies%2Fdp%2F0131422464%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1216276364%26sr%3D8-1&amp;tag=htmlist-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Core J2EE Patterns</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=htmlist-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" />&#8220;, Gamma et al&#8217;s &#8220;<a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FDesign-Patterns-Object-Oriented-Addison-Wesley-Professional%2Fdp%2F0201633612%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1216276435%26sr%3D8-1&amp;tag=htmlist-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">Design Patterns</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=htmlist-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" />&#8221; and Matt Zandstra&#8217;s &#8220;<a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FPHP-Objects-Patterns-Practice-Second%2Fdp%2F1590599098%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1216276527%26sr%3D1-2&amp;tag=htmlist-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">PHP Objects, Patterns, and Practice</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=htmlist-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" />&#8221; are all great resources for problems that come up a lot and solutions that have worked, the latter being written in PHP. Beyond that, researching how things are done in other channels of software development (or even, other industries) can provide inspiration on what can be used and reused.<br id="syr9" /></p>
<p id="v:qv27">Once you&#8217;ve identified what types of components you&#8217;d like to reuse you must ensure that your components are, first and foremost, usable. It sounds simple, but a lot of people overlook this important requirement.</p>
<h3 id="toc-what-is-actually-recyclable" id="v:qv28">What is Actually Recyclable</h3>
<p><a name="actually"></a></p>
<p id="v:qv29">I wrote a JavaScript form validation framework for a project some time back that failed horribly over the course of three projects due to my comfort with its complexity. And I was in no way a &#8220;newb&#8221; programmer at the time I developed the code. Form validation essentially came down to three components:</p>
<p>First, there was a messaging bus which allowed me to drop JavaScript message objects onto a function and have them organized and displayed to the user with pretty colors and effects.<br />
Second, I wrote a component to highlight form fields in different ways, and to present contextual messages near the elements.<br />
Third, I wrote a component to attach handlers to a form and validate the data, cancelling the form submission, running its own handler when validation failed.<br />
I was intent on keeping these parts separate so that I could switch them out as different projects required. This was not a bad thing in and of itself, but it turned bad like prom night with the quickness.<br id="hyhx" /></p>
<p id="hyhx1">As it turned out, it was too complex.  The three components had to be tied together each time, and that sucked.  I wanted to be able to switch out components with minimal incremental effort. Unfortunately, the significant effort involved in tying everything together was too much to ask from our developers.<br id="hyhx2" /></p>
<p id="v:qv30">In the middle of developing a component that we wish to reuse we are actually <em id="v:qv31">handicapped</em> by the knowledge of what the component does and how it does it. When we get feedback from other developers, their impressions are often not as descriptive as we need them to be to be able to refine our code to be more reusable. What seemed like perfectly acceptable amounts of coding to me (heck, I just wrote the thing) was a bear-like chore for others, so I ended up implementing all of the validation—a chore that was horrible itself because, as it turned out, they were right about it requiring too much coding.</p>
<p id="v:qv32">Validation required much of the fine-grained control that I had written, so I decided that my failure had to be one of documentation. I assembled some pages that defined the API and had example code for common use cases, but that didn&#8217;t fix anything. After watching Chris and David <em>not</em> use it, I left it for a while, came back, forgot how it worked, and realized how awful it was. I looked at what I was doing and realized that I was essentially rewriting much of the same code over and over. So I built a new type of validator, the <strong>SimpleValidator</strong>.<br id="hvow" /></p>
<p id="v:qv33">The SimpleValidator allows you to assign a function to a named element in a form, and if that function returns a string, the validator fails and gives the user all the string collected in this method.  Everything else happens magically, behind the scenes.  To create a SimpleValidator, you called one of the factory methods on the constructor that tailors things to your concerns.<br id="ghng" /></p>
<p id="c:mi1">The last thing I did was make a library of functions for common validation &#8220;schemes&#8221;, like email addresses, names, numbers, zip codes, et cetera, to streamline the process further. I avoided coupling the components by simply defining the factories for the different object in a SimpleValidator settings object.</p>
<p id="v:qv34">That worked well 98% of the time. For the other 2% we could still dig through my documentation and figure out how to add the element via the older interfaces so that the required behavior could be accomplished at the cost of making the coupling concrete—a tradeoff we accepted happily.<br id="k1c01" /></p>
<p id="v:qv35">Our final version was reusable because it had factories that corresponded to use cases. Adding a simple form validation script required little more than a list of what elements were of what type. Extending this behavior was easy as well, as the developer could simply wrap the existing validation function in another function which had further behavior defined. And since the low level mechanics were still all there and documented, when times got rough we simply reverted to that API and were able to achieve our desired behavior. I&#8217;ve been referring to this property of a software component as having a &#8220;degrading API&#8221;.</p>
<p id="v:qv36">If we did not have this low level access to the component, the product would be abandoned when times got tough, new solutions would be introduced into the code base, and along with them we&#8217;d be adding confusion as to which component to use where. This happened with our security component some time back, and it was horrible. During testing no one knew what was going on when a security fault occurred. We just ran around flailing and screaming until someone would hug us down from our panic. <em>[It's true, we prefer to be hugged down from our many, many panics.—Ed]</em></p>
<p id="v:qv37">With form validation, we did not just create a degrading API for developers to work with, we created the <em>right</em> API for them to work with. In short, we read their freaking minds. You&#8217;re a bit spooked by this thought, I can sense that. Calm down—deep breaths. I&#8217;ll show you how.<br id="gkno" /></p>
<h3 id="toc-ensuring-recyclability-communication" id="v:qv38">Ensuring Recyclability &#8211; Communication</h3>
<p><a name="communication"></a></p>
<p id="v:qv39">One way for those unfortunate souls among us who can<em>not</em> read minds to arrive at acceptable component boundaries and API is to talk to the other developers in the team and get their input.</p>
<p id="v:qv40">For another project we needed to build a star rating system. This means we needed an input for users to select a number of stars, and an ouput that would show the number of stars an item has received. After some time with Photoshop, I decided to use one image of stars in different states. I&#8217;d reuse this image for each of the 5 stars and have hidden radio buttons storing the state of the object. After talking with our JavaScript guy (me) about if I should do this in PHP or in JS, we decided JS was the way to go. You&#8217;d be surprised the number of times an internal dialogue-turned-external has solved problems AND frightened everyone else in the office to their very core.</p>
<p id="v:qv41">Next I talked to the developers who would be working with this object and the CSS guy who would be styling this site. The developers liked the idea of just using an input element and having everything happen magically, but the stylists and JavaScripters were concerned about having low level access to the internals. We ended up doing the following:</p>
<ul id="v:qv42">
<li id="v:qv43">Created a settings <strong>singleton</strong> that can contain much of the complexity of defining each Stars object (This allows developers to use the default settings, modify it to suit their own needs, and forget it, Ron Popeil style.)</li>
<li id="v:qv44"> Created a constructor in JavaScript that allows for an arguments object where we can override the settings singleton. This way developers can keep their settings in a convenient, easy-to-use object.</li>
<li id="v:qv45"> Created a static factory method which converts an input element of type=&#8221;star&#8221; into our model, copying the required attributes (such as class, style and id) as necessary.</li>
<li id="v:qv46"> Created a static method that trawls (getElementsByTagName) the DOM&#8217;s input elements and replaces the type=&#8221;star&#8221; ones with Stars objects.</li>
<li id="v:qv47"> Allowed setting a &#8220;disable&#8221; attribute in the arguments of the constructor, or in the settings, or searched for a disabled attribute on the input element, which caused the dynamic behavior not to be added making it a presentation only element.</li>
</ul>
<p id="ena-2">This allowed our HTML guys to write things like <code id="v:qv49">&lt;input type="star" name="rating" value="4.5" size="5" /&gt;</code> and <code id="v:qv50">&lt;input type="star" value="4.5" size="5" disabled="true" /&gt;</code> and have it automagically created. The code is semantic—you understand what it is doing by reading it.   The JavaScript people (that&#8217;s me again) demanded error reporting through <code id="v:qv51">window.console</code> if it exists, so we added that as well. Then we documented the crizazzle out of it. In this way, the API also degrades across our levels of concern for customization.<br id="g_y2" /></p>
<p id="v:qv52">Using <code id="v:qv53">&lt;input type="star" name="{element name}</code><code id="v:qv54">" value="{float}" size="{max}" /&gt;</code> seemed to encapsulate the required logic for incorporating star-ratings into a web form to such a degree that it became almost memetic. Using any other way to define the star-ratings seemed unnaturally complex and offputting. It was easy to integrate the feature all across the project and into other projects. That was the sure-fire sign that we had something good.</p>
<h3 id="toc-ensuring-recyclability-composition" id="v:qv55">Ensuring Recyclability &#8211; Composition</h3>
<p><a name="composition"></a></p>
<p id="v:qv56">Whenever I hear &#8220;API,&#8221; my mind automatically goes to a dark place of interface definitions and return type declarations for some class. This is fine for when we&#8217;re addessing a concern unique to a specific class, but if we wish to add functionality across many classes we run into trouble with that dark visage.</p>
<p id="v:qv57">One place in which we&#8217;ve seen this play out is in the Observer pattern. The <a title="Standard PHP Library" href="http://www.php.net/~helly/php/ext/spl/">Standard PHP Library</a> (SPL) has interfaces for <a href="http://www.php.net/~helly/php/ext/spl/interfaceSplSubject.html">SplSubject</a> and <a href="http://www.php.net/~helly/php/ext/spl/interfaceSplObserver.html">SplObserver</a>, and this leads people down the natural road of inheritence. Indeed, many projects use a God class from which all other objects extend. This sucks for three reasons I&#8217;ll explain and a few more that you can discover for yourself.</p>
<p>First, since late static binding is still due in PHP 5.3, there is difficulty in knowing what class you&#8217;re in if you&#8217;re not in an instance.<br />
Second, it sucks because everything gets that logic whether you want it to or not.<br />
Third, it sucks if you want to use two such projects since they each demand their own &#8220;one true God&#8221; class. It is quite the jihad to get them to work together, ha ha, no I kid, I kid.  But seriously, if you make the God classes extend another class, then updating your libraries will overwrite the changes and you&#8217;re stuck going through re-applying the changes, and it&#8217;s nothing short of a crusade. <em>[Way to diversify your religious warfare references.—Ed]</em><br id="h3r_" /></p>
<p id="v:qv58">The alternative is to implement the interface each time. The book &#8220;PHP Objects, Patterns, and Practice&#8221; by Matt Zandstra (which is an excellent book for which I have both the first and second editions) suggests doing just that (pg 204, 2nd ed.) But such an approach is so unpalatable that there is talk of adding mixins to the PHP language proper so that you can define functions once and have them mixed into your object definitions as a kind of pseudo-multiple-inheritence. We couldn&#8217;t wait for the language to change, so we had to come up with a solution then and there.</p>
<p id="eg:z0">Martin Fowler talks about the often underused power of composition in PEAA, and we decided that his books had enough pages to be right. We decided to create an Event object that would handle all of the event interactions and be composited within our existing objects. (Later on we discovered that <a id="liai" title="Symfony" href="http://www.symfony-project.org/book/1_1/17-Extending-Symfony">Symfony</a> uses a similar approach.)  This made adding event capabilities to existing classes very simple. We could even decorate (via extension) most classes that we had no control over and give them event support.  In the worst case situation, we could have an event registry that dispatches the proper event object for each object given as argument.  <br id="hj78" /></p>
<p id="v:qv60">Our composition programme took about four hours with unit tests. First, we made the constructor protected and created a factory function that took a string or object, and an array of event types and returned an event manager. The factory always returns the same object (<code id="v:qv61">===</code>) for whatever string or object is passed in as an argument and registers the event types with the event manager. When it registers the event types it adds new ones as they appear in the array. This means that if a parent constructor creates an event manager, and then our constructor &#8220;remakes&#8221; it, there will still only be one event manager linked to our object and it will have a valid list of all the available event types as well.</p>
<p id="v:qv62">We created the event manager with an array access interface. The interface maps the name of the event to an event host that was contained in the manager. The host implements <a href="http://www.php.net/~helly/php/ext/spl/interfaceSplSubject.html">SplSubject</a> and is the point of contact for the event. Then we added the <a href="http://www.php.net/~helly/php/ext/spl/interfaceSplObserver.html">SplObserver</a> interface to our function reference class and demanded that event registrars use SplObserver.<br id="ecvg" /></p>
<p id="v:qv63">The end result is that we can add event handling capabilities to a class by simply making a decorator with an <code id="v:qv64">Event_Manager $events</code> property, and we can cause things to happen as simply as <code id="v:qv65">$this-&gt;events['onToString']-&gt;fire();</code> and <code id="v:qv67">$Obj-&gt;events['beforeSave']-&gt;attach( $FuncRef );</code>.  We also created an event class that is passed to the listeners. This event allows the listeners to cancel the event, perform actions on the firing object, or modify the values being output (like Intercepting &#8220;Filter&#8221; from Alur et al).</p>
<h3 id="toc-the-carrying-cost" id="v:qv73">The Carrying Cost</h3>
<p><a name="carrying"></a><br />
The cost I most overlook when it comes to software reuse is the carrying cost—that is, how much it costs to bring your reusable components into your workspace and make use of them.  On the web, this problem is significantly larger because we&#8217;re often straddling multiple languages that may lack an engineered solution for ensuring the proper resources are made available to the browser.  PHP&#8217;s <a href="http://us2.php.net/autoload">autoload</a> functionality is nice, but don&#8217;t ask it for an image referenced in a JavaScript include.  You&#8217;ll just be disapointed (like junior prom).  A further problem for PHP is that we&#8217;re building up and tearing down everything each time, so we need methods of importing components to be shallow and cachable.<br id="y-ml" /><br id="y-ml0" />The problem I kept having was that I needed to pass information from PHP&#8217;s environment to JavaScript imported into an XHTML document, and in that JavaScript document, I needed to reference other resources that were relative to the script file.  CSS gets this right in that references to images in external CSS documents are read relative to the CSS document path.  JavaScript, surprise, does no such thing.  Plus, some scripts need to occur at certain locations in the document (which can be surmounted by the event stack in IE or the event queue in Firefox; if you feel the urge to cut yourself, you&#8217;re doing it right.) Finally, some scripts must be included <em>before</em> others, but I didn&#8217;t want to throw errors when someone imported one component before another.  <br id="sfiu" /><br id="sfiu0" />We built something called Axon, which, for lack of a better description, allows for something like Java&#8217;s import statements.  A package definition file (there can be any number of them) describes resource names like &#8220;Synapse.Forms.Validation&#8221; and maps them to required resource names (dependencies) and resource paths associated to channels.  A channel was the end resource type, such as &#8220;CSS&#8221; or &#8220;JavaScript&#8221;, and mapped onto the Loader to manage which things are imported.  Further, Axon recursively met the dependencies to ensure things entered the environment in the proper order.  Lastly, we added a service definition so that a resource could describe itself as providing, say, &#8220;sendEmail&#8221;, and allowed the loader to be queried for a service.<br id="nm1q" /><br id="nm1q0" />Axon &#8220;worked&#8221; in that it made using our messaging bus system and form validation code easy. We used it everywhere.  It failed in that we never used services, and no one remembers if caching is on or off, causing comically bad situations where bug fixes don&#8217;t work or, alternatively, performance tanks.  Both great options.</p>
<p>Also, I was pretty much the only person to ever write things into Axon, and I never documented it well.  We ended up using the PEAR style name-to-directory convention convention for PHP objects and directly modifying our templates for most code for what I am told are &#8220;performance issues.&#8221;<br id="qu47" /><br id="qu470" />The toe-hold that Axon had with the bus and form validation meant that it stuck around, and we slowly began to add more things to it that were useful (although the issues with caching persisted.)  But the down side of sticking around is that we&#8217;re stuck with it.  No mana-jerks want to budget time to give it an overhaul, and we developers couldn&#8217;t agree on how to fix it.    Currently we&#8217;re rotating out a portion of our <a href="http://www.synapsestudios.com/projects/canopy/">Canopy framework</a> in favor of Zend&#8217;s framework so we might abandon Axon altogether (although we&#8217;ll keep the name for something else), but if we weren&#8217;t in such turmoil and tumult we might well be stuck with Axon <em id="mwzj">ex infinitum</em>. <br id="hhp-0" /></p>
<h3 id="toc-hard-choices-about-recycling" id="hhp-1">Hard Choices About Recycling</h3>
<p><a name="choices"></a></p>
<p id="v:qv74">Some people (probably from the Drupal project) will note that composition has more performance overhead than directly defining the observers and subjects using the SPL interfaces. Yes, that&#8217;s true, especially in PHP. But that&#8217;s nothing compared to the performance overhead of PHP itself—you can make Java do some wicked fast things if you&#8217;ve got the time to write it. But we write in interpreted languages like PHP because it speeds development and deployment. That leaves us with some hard choices to make. For code recycling to work, like real recycling, it has to save money.<br id="jvdc" /></p>
<p id="v:qv75">For projects like Drupal and WordPress, performance is an issue since people will be adding to them, and if the project is a performance hog to begin with, these additions will bog down performance further and the product will become unusable.  But performance is neither paramount nor sacrosanct.  You can spend real cheese on optimizing a system where adding more hardware may be a much cheaper solution.  Many projects we work on are fluid—that is to say, they require the ability to quickly and cheaply add new features and change according to their communities needs.  The added time for developers to work through the mess of optimization often is more expensive than just adding hardware to compensate for less-than-stellar code.</p>
<p id="k.n31">Now I&#8217;m not advocating solving all performance issues by throwing hardware at it.  That&#8217;s a terrible idea.  Terribly terrible.  But look at the cost of resources and where your project is going.  It may make sense (apologies for what I&#8217;m about to say) to prototype and start with PHP and then create a Java-based solution when the project is mature (maybe a few years later).</p>
<p id="v:qv79">As PHP developers we find ourselves in a community that prides itself on open source. That pride means that every single one of us has downloaded WordPress, Drupal and Magento, looked at the source, and wondered &#8220;What the F double hockey sticks is this about?&#8221; With open source, the reuse ballgame is much wider.  We&#8217;re targeting and being the targets of a much larger community of developers.</p>
<p>In open source projects, your code has to make sense to users from China to Oklahoma and let me tell you, there are some cultural divides there.  The documentation has to be written and translated.  And the scale of the larger open source projects usually means that reuse is limited to building your own items into their pre-existing frameworks.  I always hope to find a tier separated from display so that I can envoke and operate on an application&#8217;s data object, but it rarely ever works out that way.  Perhaps it&#8217;s a case of cyber-myopia, but the successful large OSS projects seem to emphasize ease of deployment and customization over individual component reuse.  This is not the case for many of the projects self-identifying as &#8220;frameworks&#8221;.<br id="piko" /></p>
<p id="piko2">There is an explosion of PHP frameworks and JavaScript frameworks, and the ones that have made themselves available as toolkits as well as frameworks (or, as David likes to call them, &#8220;component frameworks&#8221;) have been able to weather the storm (and garner more attention).  Similar to my form validation class, I think success in the open source world requires a low cost to deployment, degrading API&#8217;s and proper separation of concerns.<br id="ppvr" /></p>
<p id="ppvr2">By making your code open source and available you can get feedback worth it&#8217;s weight (if printed on gold paper) in gold. Further, people who use the project will also make improvements. I posted a REST interface to Amazon&#8217;s S3 in response to a request on the Zend frameworks list some time ago, and the requester kindly made it function with streams (which I knew nothing about at the time). In relying on the (all too) true fact that there are people way smarter than me on the internet, we both got something very useful.</p>
<h3 id="toc-conclusion" id="v:qv80">Conclusion</h3>
<p><a name="conclusion"></a></p>
<p id="v:qv81">My psychic abilities tell me you&#8217;re wondering why this wall of text was worth your time. It probably wasn&#8217;t. (This is especially true if you&#8217;re Martin Fowler, man am I ever wasting your time, Martin, and I&#8217;m sorry.) For PHP developers especially, notice that as we make our code more meaningful <em id="v:qv82">ad face</em>, we may be sacrificing speed on the processor but we&#8217;re gaining huge amounts of development time, bug tracking time and fees for busted keyboards and restraining order hearings. That&#8217;s the hard sell—as a developer we have to deal with costs, and as PHP developers we have the advantage of being on an already &#8220;slow&#8221; interpreted language rather than writing assembly into our C++ for speed.</p>
<p id="v:qv83">By focusing on reuse we gain savings directly and indirectly, as reusable components serve as a vocabulary to discuss a project.  We all feel the need for it, but it&#8217;s difficult to secure a way to ensure reuse. In an effort to sum up, I am suggesting requiring the following in your own projects:</p>
<ul id="v:qv84">
<li id="v:qv85"> Require that concerns be addressed one domain at a time, and composite those solutions as needed</li>
<li id="v:qv86"> Focus on writing semantic code (for which the meaning is obvious from its structure)</li>
<li id="v:qv87"> Document your code and include example use cases</li>
<li id="v:qv88"> Documentation should always include a description of what you are trying to achieve as well as what you are <em>actually</em> achieving with your design.  Be honest</li>
<li id="v:qv89"> Use composition over inheritence when adding features to multiple classes from the past, present and future (mainly when spanning different codebases)</li>
<li id="v:qv90"> Allow for high level uses via factories</li>
<li id="v:qv91"> Allow for low level uses via constructors and factories.<br id="k1ci" /> (When PHP 5.3 lands, don&#8217;t let your constructors be public)</li>
<li id="v:qv92"> When something will be constant for a long time, provide a place to put that data once and reuse it, don&#8217;t demand it each time</li>
<li id="v:qv93"> Talk to people who will be developing with this piece of code, or pretend you are them, or actually <em>be </em>them and learn what concerns they have</li>
<li id="v:qv94"> Imagine refactoring an older project to use this code. Ask yourself what problems you forsee, and how can you make design decisions now to prevent these problems?</li>
<li id="v:qv95"> Release your code to a community that can use it (and ensure they can use it by releasing it at GPL3 or better.) Encourage feedback and participation</li>
<li id="v:qv96"> Drink a lot of vodka and red bull and black out when you code so that you can approach it with a fresh mind the following day</li>
<li id="v:qv97">Request comments at every stage,  examine the gap between what they expect and what you&#8217;re planning on building, but ignore feature requests that would cause you to drift off target.  Do not try to complete components all at once, rather let it be something to which you come back.  Don&#8217;t rush it, just let it happen, baby<br id="rztk" /></li>
<li id="v:qv98"> Do not fear trading small amounts of performance for semantic structure. You&#8217;re not developing mainframes or nuclear stockpile simulators, you&#8217;re building web apps in PHP and more often than not the most expensive thing is you, so pamper yourself</li>
<li id="nfpa"> Be able to say that something is not a good candidate for re-usability.  If, over the course of time, you begin to notice yourself re-writing it again and again in a way that can be abstracted, then go for it, but it&#8217;s okay if not everything is part of a library</li>
<li id="mt7g"> Be willing to use (or willing to consider using) existing libraries for reusable components.  It will get you in the mindset of your community and provides you with a bunch of tools you don&#8217;t have to build yourself</li>
</ul>
<p>If you do these things, you&#8217;ll get rich quick working from home.  No, not really, you won&#8217;t, at least you probably won&#8217;t, because the results I&#8217;ve cited are not typical.<br id="mef3" /> <br id="mef30" /> In fact, in the spirit of this article I hope any reader who makes it to this point writes a post on their own experience—what&#8217;s worked and what&#8217;s failed.  My psychic abilities tell me that several of you read this and said &#8220;whoa, that&#8217;s a recipie for a performance disaster,&#8221;  and when projects explode in popularity this criticism is most certainly true.  My &#8220;Highly Available Enterprise Application Architecture with PHP&#8221; post is twice as long and three times as ornery.  Also it is entirely written in Tamarian allegory regarding Darmok and Jalad.  But with Thrift, Smarty-like templates, EC2, a smart caching strategy, APC, memcached and a little shuffling of resources you can rebound.</p>
<p>Now go hit the vodka red bulls and let us know your thoughts.</p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=114&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/development/the-lazy-clever-programmer-a-compendium-of-code-reuse-and-recycling/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Enterprise Patterns: A Look At Application Service</title>
		<link>http://www.htmlist.com/development/php-enterprise-patterns-application-service/</link>
		<comments>http://www.htmlist.com/development/php-enterprise-patterns-application-service/#comments</comments>
		<pubDate>Mon, 23 Jun 2008 08:08:03 +0000</pubDate>
		<dc:creator>David Bernal</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[application service]]></category>
		<category><![CDATA[enterprise]]></category>
		<category><![CDATA[front controller]]></category>
		<category><![CDATA[model view controller]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[software patterns]]></category>

		<guid isPermaLink="false">http://www.htmlist.com/?p=69</guid>
		<description><![CDATA[There is considerable confusion on the internet about the proper placement of complex business logic when using the MVC pattern. In this post, we look at another pattern we can use to solve this problem in an elegant way.]]></description>
			<content:encoded><![CDATA[<p>Today we’re going to talk about PHP enterprise patterns and all the fun they bring to the party. We’ll get into front controllers and take a close look at MVC as well.</p>
<h4 id="toc-towns-buildings-construction">Towns, Buildings, Construction</h4>
<p>So let&#8217;s talk about patterns. Specifically, I&#8217;d like to talk about the MVC architecture pattern, and some thoughts I&#8217;ve had recently regarding its application. Let&#8217;s first clear the air a bit, make sure everyone is limber, and define our terms. It may be unknown to some that the seminal work in patterns, <a href="http://en.wikipedia.org/wiki/A_Pattern_Language" target="_blank">A Pattern Language: Towns, Buildings, Construction</a>, was actually about architecture (the kind with buildings) and urban planning, not software design. One of the key observations the author makes in the book is that many cities which are laid out in a practical and attractive manner follow a similar pattern, which was varied depending on the exact situation. This is exactly how patterns in software architecture work; Patterns are elegant solutions to common problems that are flexible enough to be applied to differing scenarios.</p>
<p><span id="more-69"></span></p>
<h4 id="toc-the-venerable-mvc">The Venerable MVC</h4>
<p>MVC is one of the most common patterns, especially in web development. MVC is an architecture pattern, which means that it defines several distinct responsibilities in an application, and describes a set of objects, each of which fulfills one of those responsibilities. Specifically the MVC in MVC stands for model, view and controller. Different implementations define the responsibilities differently, but roughly they are defined as follows: (that&#8217;s right, I&#8217;m so semantic I&#8217;m about to use the <a title="DL Tag" href="http://www.w3schools.com/TAGS/tag_dl.asp" target="_blank">&lt;dl&gt; tag</a>)</p>
<dl>
<dt>Model</dt>
<dd>Represents the data used by the application, tends to also hold some amount of business logic. Also facilitates persistence (often by using or encapsulating some kind of data abstraction layer).</dd>
<dt>Controller</dt>
<dd>Handles events, may make changes to the model.</dd>
<dt>View</dt>
<dd>Generates an appropriate interface (such as an HTML page).</dd>
</dl>
<p>This isn&#8217;t quite the whole story, and I&#8217;m not really interested in telling the whole story, but I&#8217;d like to add a little bit more. Most MVC applications will use a <a href="http://www.martinfowler.com/eaaCatalog/frontController.html">front controller</a> to dispatch incoming requests. The front controller will itself use a variety of helpers to actually invoke Controllers and Views, but the diagram below represents a simplified lifecycle diagram for a typical MVC application implemented in PHP.</p>
<p><a href="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc.png"><img class="aligncenter size-full wp-image-70" src="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc.png" alt="Basic MVC sequence diagram" width="500" height="241" /></a></p>
<p style="0 auto;"><a href="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc.png"><br />
</a></p>
<h4 id="toc-fear-and-doubt">Fear and Doubt</h4>
<p>A question that ought to arise after a brief period of thought and maybe a few sips of your coding-beverage of choice (mine is usually a latte or Dr. Pepper) is, &#8220;Where in the HELL am I supposed to put my business and application logic?&#8221; There has been a fair bit of discussion and ensuing misinformation about this one on the interwebs.</p>
<p>Some recommend that business logic be placed in the controllers. Controllers (both Front and Application), however, exist to control program flow; they do things like delegating routing, creating views, and invoking models. Furthermore, if a developer implements application logic in their controllers, they have essentially coupled the method of <em>accessing</em> a feature to the <em>implementation</em> of that feature. This means that changing URL patterns, or allowing different URLs for accessing the data in different ways requires code duplication, or ugly hacks to the routing system.</p>
<p>From there, then, it would appear to make sense to implement business logic on the model itself. Recall, however, that the model is really about encapsulating the data. Putting business logic in the model allows direct access to that data, rather than access to an interface. This results in a tight-coupling between the model and application logic. Reuse is hurt, because functionality specific to an application gets built into the model. Later users who require a different set of functionality but wish to access the same model are forced to either rewrite the models, or live with a bunch of crufty code written for the previous project. Logic which works on multiple objects clearly does not belong in any of the objects it uses. It becomes clear that we must take a different tack.</p>
<h4 id="toc-a-different-tack">A Different Tack</h4>
<p>Since we want to decouple application features from program flow, as well as from the underlying data they access, the solution is to implement some fourth class that allows access to those features, rather than to program flow, or to data. In <a href="http://www.corej2eepatterns.com">Core J2EE Patterns</a>, which is a great read and the inspiration for this post, this is referred to as the application service pattern. An application service object allows access to application features, hiding the underlying logic and abstracting the data access further. Note that use of an application service does not exclude direct access to models when it makes sense; it merely provides another option when logic should be decoupled from the model. We now modify the above sequence diagram to demonstrate the application service pattern in action.</p>
<p><a href="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc-as.png"><img class="aligncenter size-medium wp-image-73" src="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc-as-300x147.png" alt="MVC with application service" width="300" height="147" /></a></p>
<p>Note that addition of the ApplicationService, which sits between the Controller and the Models. When the Controller needs access to a feature provided by an application service, it accesses that ApplicationService. On the other hand, when more direct access to the data is required, the option to access the model directly still exists.</p>
<h4 id="toc-handling-online-payments-an-example">Handling Online Payments: An Example</h4>
<p>By now, I&#8217;m sure you&#8217;re thinking one thing: &#8220;What is all this hibbity-jibbity and gobbledygook?&#8221; Let&#8217;s do an example. Suppose you&#8217;re handling payments on your website. You have a transactions table which stores the payment status, the email addresses of the parties involved, and transaction id received from the gateway, and an invoices table, which stores the amount due, invoice due dates, and so on. You also have the corresponding models, which encapsulate simple <a href="http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete">CRUD</a> operations on this data.</p>
<p><a href="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/database-2.png"><img class="aligncenter size-full wp-image-76" src="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/database-2.png" alt="Database diagram" width="331" height="139" /></a></p>
<p>When the payment status changes, the server receives an XML formatted request. When this happens, a script should verify the data received by posting it back to the gateway server. If the data received is valid, it should store that information in the transactions table, and update the invoices table to reflect the new information. It makes sense to implement the validation functionality on the Transactions model, because that functionality operates only on the data encapsulated by that model, and because there isn&#8217;t a case where you would want to use that model without using the validation functionality.</p>
<p>It doesn&#8217;t make sense, however, to implement the logic that decides what to do once the data has been validated on the Transactions model. A payment gateway is something very likely to be reused, but the invoice\billing module will differ from project to project. It also doesn&#8217;t make sense to implement this logic on the Invoices model either, because that would couple the invoices to the payment gateway, and violate separation of concerns.</p>
<p>It therefore makes sense to implement an application service that handles this logic. The sequence diagram below represents the program flow using the application service pattern as described. Note that the controller still uses the Transaction model directly to access its data, before sending it to the view.</p>
<p><a href="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc-as-ex.png"><img class="aligncenter size-medium wp-image-75" src="http://www.htmlist.com/wordpress/wp-content/uploads/2008/06/mvc-as-ex-300x148.png" alt="Sequence diagram of example" width="300" height="148" /></a></p>
<h4 id="toc-blog-post-requirement-fulfilled">Blog Post Requirement: Fulfilled</h4>
<p>So, we&#8217;ve fulfilled my blog post requi—er, defined a more elegant way of providing access to application services. To summarize the factors that lead us to the application service, we wanted to provide complex application features that operate on multiple objects without polluting those objects or increasing tight coupling between them. By abstracting these features away from the model, we enhanced reusability of the models and preserved separation of concerns. Similarly, by removing functionality from the controller, we decoupled application functionality from program flow.</p>
<p>Please contribute your comments and experiences with MVC and other patterns in developing for the web.</p>
<img src="http://www.htmlist.com/wordpress/?ak_action=api_record_view&id=69&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.htmlist.com/development/php-enterprise-patterns-application-service/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
