<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title><![CDATA[Mat Byrne .com]]></title>
    <link>http://www.matbyrne.com/</link>
    <description><![CDATA[Web Design & Development]]></description>
    <pubDate>Sun, 15 Nov 2009 14:38:38 +0000</pubDate>
    <managingEditor>mathewbyrne@gmail.com (Mathew Byrne)</managingEditor>
    <generator>mblog 0.1</generator>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/matbyrne" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
      <title><![CDATA[Extending Functions in Javascript]]></title>
      <link>http://feedproxy.google.com/~r/matbyrne/~3/UcWh8WQK4cs/extending-functions-in-javascript</link>
      <guid isPermaLink="false">http://www.matbyrne.com/2008/7/10/extending-functions-in-javascript</guid>
      <description><![CDATA[<p>Lately I&#8217;ve been writing a lot of Javascript, definitely a trend that I expect to continue for the foreseeable future. While working on a recent project I came across the following problem:</p>

<pre class="sh_javascript">var condition = another_condition = true; // For this example to work!

function animate (callback)
{
    c = (typeof(callback) == 'function') ? callback : function () {};

    if (condition) {
        c = function () {
            c();
            console.log('bar');
        };
    }

    if (another_condition) {
        c = function () {
            // More functionality.
            console.log('baz');
            c();
        };
    }

    c();
}

animate(function () { console.log('foo'); });
</pre>

<!--more-->

<p>My intent was to allow a function reference to be passed into  <strong>animate()</strong>, and modify the reference so that additional functionality would be added depending on the evaluation of several conditions.</p>

<p>Assuming that both <strong>condition</strong> and <strong>another_condition</strong> evaluated true I had expected the output of the above to be:</p>

<pre class="sh_javascript">baz foo bar
</pre>

<p>Of course this isn&#8217;t what happened. The output was something like:</p>

<pre class="sh_javascript">baz baz baz baz baz baz baz &hellip;</pre>

<p>&hellip;before my browser crashed.</p>

<h2 id="what_happened">What happened?</h2>

<p>What happened was simple, yet it&#8217;s cause was an obscurity of Javascript closures; the variable <strong>c</strong> changed to reference 3 different functions during the course of this code execution. Initially it pointed to the function reference passed into <strong>animate</strong>, however when <strong>condition</strong>, and later <strong>another_condition</strong> evaluated true, <strong>c</strong> was reassigned once, then again to now be a reference to the later newly created anonymous function.</p>

<p>I was aware than due to the phenomenon that is closures that each newly created function would have full access to <strong>c</strong> and be able to call the function directly. What I didn&#8217;t expect was that this function reference would not be dynamic and not necessarily reference the function that <strong>c</strong> referenced at the time the function was created.</p>

<p>So when <strong>c</strong> was called, all it ended up doing was calling itself recursively, repeatedly logging &#8216;baz&#8217;, and eventually overflowing and crashing Firefox.</p>

<h2 id="the_solution">The Solution</h2>

<p>Obviously references to <strong>c</strong> would need to be stored somewhere for later retrieval. The solution was to store a reference to the current value of <strong>c</strong> in a local anonymous namespace.</p>

<pre class="sh_javascript">var condition = another_condition = true; // For this example to work!

function animate (callback)
{
    c = (typeof(callback) == 'function') ? callback : function () {};

    if (condition) {
        (function () {
            var oldC = c;
            c = function () {
                oldC();
                console.log('bar');
            };
        })();
    }

    if (another_condition) {
        (function () {
            var oldC = c;
            c = function () {
                console.log('baz');
                oldC();
            };
        })();
    }

    c();
}

animate(function () { console.log('foo'); });
</pre>

<p>Not the neatest Javascript example I&#8217;ve ever written, but nevertheless this is an very powerful javascript pattern.</p>

<p>My particular use case was a fairly complex animation routine in which sections of the routine could be turned on or off. The callback passed in would be augmented in this fashion in order to ensure it would execute when the animation was complete.</p>

<p>However the solution above isn&#8217;t very scaleable; the code repetition seems to suggest that a useful abstraction could be added.</p>

<pre class="sh_javascript">Function.prototype.extendFn = function (fn) {
    var c = this;
    return function () { fn(c); };
};

// Alternative, for those who don't like modifying Function.prototype:
var extendFn = function (callback, fn) {
    var c = callback;
    return function () { fn(c); };
};
</pre>

<p>The original code can now be rewritten:</p>

<pre class="sh_javascript">var condition = another_condition = true; // For this example to work!

function animate (callback)
{
    c = (typeof(callback) == 'function') ? callback : function () {};

    if (condition) {
        c = c.extendFn(function (c) {
            c();
            console.log('bar');
        });
    }

    if (another_condition) {
        c = c.extendFn(function (c) {
            console.log('baz');
            c();
        });
    }

    c();
}

animate(function () { console.log('foo'); });
</pre>

<p>And will work as expected, printing:</p>

<pre class="sh_javascript">baz foo bar
</pre>

<p>Much better! This solution was perfect for my particular use case, and I can see it being a useful functional programming pattern.</p>

<p><strong>Update:</strong> Apologies for not mentioning this earlier, but thanks to the folks on Freenode's <strong>#javascript</strong> IRC channel, in particular <strong>joekarma</strong> for his original solution and suggestions. This post came out of a conversation yesterday in which we discussed possible solutions similar to those given above.</p>

]]></description>
      <pubDate>Thu, 10 Jul 2008 01:11:03 +0000</pubDate>
    <feedburner:origLink>http://www.matbyrne.com/2008/7/10/extending-functions-in-javascript</feedburner:origLink></item>
    <item>
      <title><![CDATA[Dynamic Domain Objects in PHP]]></title>
      <link>http://feedproxy.google.com/~r/matbyrne/~3/FnGaY4Ie4lk/dynamic-domain-objects-in-php</link>
      <guid isPermaLink="false">http://www.matbyrne.com/2008/4/20/dynamic-domain-objects-in-php</guid>
      <description><![CDATA[<p>Modeling real-world objects with computer Data Structures is one of the more fundamental principles of Computer Science.</p>

<p>Data Models however are often tied heavily to their storage medium, whether that be an SQL database, files on a filesystem or a web-service. The idea of implementing a Model/Mapper system is to decouple the format in which we wish to manipulate data from the format that we store it.</p>

<!--more-->

<p>PHP is a great language to attempt something like this. It&#8217;s dynamic nature allows us to create complex Domain Objects with a large range of functionality with minimal setup.</p>

<p>In Part 1 of this tutorial I&#8217;m going to show you how to build a generic Model base class from which you can easily extend concrete classes for use in your application.</p>

<p>In Part 2, I&#8217;m going to explore the role of the Mapper class, and how best to form a layer between your storage and your Domain Objects.</p>

<h2 id="not_your_average_model_class">Not your average Model class</h2>

<p>Take the following simple PHP Domain object:</p>

<pre class="sh_php">class SerialKiller
{
    private $_name;
    private $_weapon;

    public function __construct ($name, $weapon)
    {
        $this-&gt;setName ($name)-&gt;setWeapon ($weapon);
    }

    public function getName ()
    {
        return $this-&gt;_name;
    }

    public function getWeapon ()
    {
        return $this-&gt;_weapon;
    }

    public function setName ($name)
    {
        $this-&gt;_name = $name;
        return $this;
    }

    public function setWeapon ($weapon)
    {
        $this-&gt;_weapon = $weapon;
        return $this;
    }
}
</pre>

<p>Ok, it&#8217;s a little <em>unconventional</em> but I&#8217;ve been <a rel="external" href="http://en.wikipedia.org/wiki/Dexter_(TV_series)">watching a lot of Dexter</a>) lately. Highly recommended! But it does illustrate a Model class in the classic sense: a class that abstract a set of data and provides a consistent interface to access it.</p>

<p>Many will argue that this <em>could</em> be done very simply using a <a rel="external" href="http://au.php.net/oop">PHP stdClass</a> or even just a vanilla Array. What we are trying to promote here however is <a rel="external" href="http://en.wikipedia.org/wiki/Information_hiding">Encapsulation</a>; the idea is that we hide the implementation of how our Model stores it data away from our client code.</p>

<p>Now that was a fair bit of code for a class that basically allows the getting and setting of <strong>two fields</strong>. In just writing that example, I had to make at least 3 typo corrections, and that&#8217;s only for two fields.</p>

<h2 id="our_model_class_take_2">Our Model class take 2</h2>

<p>Hmmm&hellip; seems like there would be a smarter way to do this. After all we do have a <em>very</em> flexible programming language to work with. Let&#8217;s try abstracting the getting and setting somewhat:</p>

<pre class="sh_php">class SerialKiller // Mk.2
{
    private $_data = array (
            'name'   =&gt; null,
            'weapon' =&gt; null
        );

    public function __construct ($name, $weapon)
    {
        $this-&gt;setField ('name', $name)-&gt;setField ('weapon', $weapon);
    }

    public function getField ($name)
    {
        return isset ($this-&gt;_data[$name]) ? $this-&gt;_data[$name] : null;
    }

    public function setField ($name, $value)
    {
        if (isset ($this-&gt;_data[$name])) {
            $this-&gt;_data[$name] = (string) $value;
        }

        return $this;
    }
}
</pre>

<p>Ok, much more concise! The new and improved SerialKiller class gives us a couple of advantages over it&#8217;s predecessor:</p>

<ol>
<li><p>It&#8217;s become a lot more general. For instance if we wanted to add another field, we could simply add a new key to SerialKiller::$_data.</p></li>
<li><p>The code is less prone to bugs since it&#8217;s shorter, more elegant and easier to read.</p></li>
<li><p>The code is easier to maintain now since it doesn&#8217;t contain as may functions.</p></li>
</ol>

<p>However I think we can still improve more on this, say for instance I want some special functionality for the &#8216;weapon&#8217; field. Say I want it to be in a range of certain values, and if it isn&#8217;t an exception should be thrown. How would I implement this?</p>

<p>Easy you say! You would insert a quick check into the SerialKiller::setField function that checks for a field name and acts accordingly. But of course, say I have 20 fields and 5 of them require custom handling. <strong>Not a very scalable solution!</strong></p>

<p>So what&#8217;s the real problem here? The problem is twofold:</p>

<ol>
<li><p>We&#8217;ve now changed the external API to something that is <em>less</em> consistent and meaningful than our first attempt.</p></li>
<li><p>Every field is accessed by calling the <strong>same</strong> function <strong>externally</strong>. </p></li>
</ol>

<p>What we really need is a separate external function for each field that&#8217;s abstracted internally somehow.</p>

<h2 id="further_improvements">Further Improvements</h2>

<p>Remember that PHP can catch calls to non-existent functions in a class if you <a rel="external" href="http://php.net/manual/en/language.oop5.overloading.php">define a public function name __call</a>. Let&#8217;s see what use we can make of this feature:</p>

<pre class="sh_php">class SerialKiller //Mk.3
{
    private $_fields = array ('name', 'weapon');

    private $_data = array ();

    public function __construct ($name, $weapon)
    {
        $this-&gt;setName ($name)-&gt;setWeapon ($weapon);
    }

    public function __call ($fn, $args)
    {
        $type = substr ($fn, 0, 3);
        $name = strtolower (substr ($fn, 3));

        if ($type == 'get') {
            return $this-&gt;_getField ($name);
        }

        if ($type == 'set') {
            return $this-&gt;_setField ($name, $args[0]);
        }

        throw new Exception ("Function {$fn} is not implemeted.");
    }

    private function _getField ($name)
    {
        $this-&gt;_checkField ($name);

        return isset ($this-&gt;_data[$name]) ? $this-&gt;_data[$name] : null;
    }

    private function _setField ($name, $value)
    {
        $this-&gt;_checkField ($name);

        $this-&gt;_data[$name] = $value;
        return $this;
    }

    private function _checkField ($field)
    {
        if (!in_array ($field, $this-&gt;_fields)) {
            throw new Exception ("Field {$field} is invalid.");
        }           
    }
}
</pre>

<p>So there&#8217;s quite a jump between Mk.2 and Mk.3. Let me go through some of features we now have with our latest revision:</p>

<ol>
<li><p>We now have the API of the first class with the internal benefits that the second class offered.</p></li>
<li><p>We&#8217;ve abstracted the process of adding fields to our serial killer. This means that to add a field for &#8216;Age&#8217;, all we&#8217;d need is to add the value &#8216;age&#8217; to the SerialKiller::$_fields array.</p>

<p>The benefit of that is that by making that small 7 character change (, &#8216;age&#8217;), we now can call getAge and setAge on any SerialKiller instance <em>automatically!</em></p></li>
<li><p>Since __call is only called when a matching function is called and not found, we can easily introduce functionality for specific fields <strong>without</strong> altering existing functions:</p>

<pre class="sh_php">private function setWeapon ($weapon)
{
    if (!in_array ($weapon, array ('knife', 'axe', 'chainsaw'))) {
        throw new Exception ('Invalid weapon type!');
    }

	return $this-&gt;_setField ('Weapon', $weapon);

}
</pre></li>
<li><p>Our SerialKiller is now extremely generic. If we wanted to specialise his class at all, we could do so very easily. In fact, if we were to rename SerialKiller to Model and make his class an abstract one, we now have a very generic Model class capable of storing all sorts of data in a very flexible way.</p></li>
</ol>

<h2 id="in_practice">In Practice</h2>

<p>Of course I like to bring these discussions back to something more pragmatic rather than keep the theoretical SerialKiller example going.</p>

<p>In practice this class works extremely well. All our internal Model classes extend a base class not dissimilar to the one we created above. Of course we&#8217;ve fleshed out our version considerably. Here&#8217;s a brief description of some features:</p>

<ol>
<li><p><strong>Better inflection of field names:</strong> Current this class converts everything to lowercase. Not a great idea since it means that more than one function can map to a field (e.g. setName, setNAME, setnAMe etc.).</p>

<p>We like to inflect names from camel case (setFieldValue) to names that match our backend storage, usually underscore separated (field_value).</p></li>
<li><p><strong>Setting &amp; Getting fields en masse:</strong> This one is mostly useful in circumstances where you want to convert from Form data say to a Model class. We&#8217;ve incorporated this into the Constructor so creating a model from an array becomes as simple as:</p>

<pre class="sh_php">$serialKiller = new SerialKiller (array (&#8216;name&#8217; => &#8216;Dexter&#8217;, &#8216;weapon&#8217; => &#8216;knife&#8217;));</pre></li>
<li><p><strong>Marking Concrete instances:</strong> We&#8217;ve added an id field to our base Model class separate from the other fields. This acts as a marker for Model instances that ties it to a row in the database. Instances without their id set are considered volatile instances and will expire when they go out of scope if they&#8217;re not saved.</p></li>
</ol>

<p>There are hundreds of improvements you could make on the base class, and I&#8217;d strongly urge people to make improvements of their own.</p>

]]></description>
      <pubDate>Sun, 20 Apr 2008 12:42:04 +0000</pubDate>
    <feedburner:origLink>http://www.matbyrne.com/2008/4/20/dynamic-domain-objects-in-php</feedburner:origLink></item>
    <item>
      <title><![CDATA[Zend Framework in Practice]]></title>
      <link>http://feedproxy.google.com/~r/matbyrne/~3/446b0d_3CIw/zend-framework-in-practice</link>
      <guid isPermaLink="false">http://www.matbyrne.com/2008/4/18/zend-framework-in-practice</guid>
      <description><![CDATA[<p>With all the components available to a developer using <a rel="external" href="http://framework.zend.com/">Zend Framework</a>, it can definitely be a daunting task working out how best to use all the pieces to build your web applications.</p>

<p>I tend to work best through example, so let me walk-through how we use ZF in our business, and what components I used in this site to build a blogging engine. At the office we&#8217;ve been using the Zend Framework in production for about a year now. A lot has changed in the last year, but as most people who use open source software in a production environment will tell you, this is definitely common for a fairly young project like ZF.</p>

<p>Now <a rel="external" href="http://www.jbinteractive.com.au/">almost all of our projects</a> are based on ZF, and it&#8217;s modular architecture has led us to develop our own internal library which mostly houses extensions to existing ZF Components.</p>

<!--more-->

<p>This site too is also based on ZF combined with our internal library and a simple blog engine I&#8217;ve dubbed <strong>mblog</strong> until I can come up with something easier to say (that or some kind of recursive acronym).</p>

<p>The major benefit that the ZF team touts is it&#8217;s modularity and it&#8217;s  intentional lack of conventions and expectations; basically most components in ZF are design so that you can drop them into your code where it makes sense. There are a heap of benefits to this idea, and it tends to suit a lot of different approached web application development. However it also means that  often you will need to go the last mile with ZF and really customise aspects to suit your code base.</p>

<p>That said, here&#8217;s how I&#8217;ve utilised parts of ZF to build this blogging engine:</p>

<h2 id="zend_controller">Zend_Controller</h2>

<p>If you are using Zend Framework for a web application and you have the flexibility I would definitely recommend using <a rel="external" href="http://framework.zend.com/manual/en/zend.controller.html">Zend_Controller</a> as the backbone of your application.</p>

<p>ZF&#8217;s <a rel="external" href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a> implementation is very mature and supports features like complex routing and seamless view integration. It&#8217;s architecture provides an huge selection of hook points with which to integrate your own code.</p>

<p>mblog makes great use of the <a rel="external" href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html">Action_Helpers</a>, abstracting out large pieces of functionality and giving Controllers a simpler interface with which to execute and manage that functionality.</p>

<p>One example of this would be the <a href="#add_comment">comments form</a> on every article page. All form creation and management (including setting cookies, managing form data etc.) is managed by an Action Helper. This is bridged to the view with a View Helper making access to the comments form easy from both controller and view code.</p>

<h2 id="zend_feed">Zend_Feed</h2>

<p>Although <a rel="external" href="http://framework.zend.com/manual/en/zend.feed.html">Zend_Feed</a> is aimed more at consuming feeds, it does have the ability to generate dynamic feeds and provides a nicely abstracted set of base classes for you to implement custom feed types.</p>

<p>In this case the <a href="/feed">main site RSS feed</a> is generated by passing an array of all current articles to the RSS feed and letting Zend_Feed generate the XML required.</p>

<h2 id="zend_db">Zend_Db</h2>

<p>Internally at <a rel="external" href="http://www.jbinteractive.com.au/">JB Interactive</a> we don&#8217;t tend to use many of the Zend_Db components directly. Instead we have a Domain Model/Mapper layer (<a rel="external" href="http://loveandtheft.org/2008/04/07/domainobject-and-datamappers/">see here</a> for a great article that describes a PHP implementation of this pattern) that sits between application code and the database. I&#8217;ll save Jb_Model for a later blog post, but in generally I find the Zend_Db classes somewhat too heavy for widespread application use.</p>

<p>That said, the <a rel="external" href="http://framework.zend.com/manual/en/zend.db.select.html">Zend_Db Select API</a> is fantastic and more or less gives you all the functionality of custom SQL queries with an OO interface.</p>

<p>In particular blog posts are retrieved and filtered using the select API, and
the following is possible:</p>

<pre class="sh_php">public function getPageByDetails ($slug, $year, $month, $day)
{
    $select = $this-&gt;_table-&gt;select ()
        -&gt;where ('slug = ?', $slug)
        -&gt;where ('YEAR(date_created) = ?',  (int) $year )
        -&gt;where ('MONTH(date_created) = ?', (int) $month)
        -&gt;where ('DAY(date_created) = ?',   (int) $day  );

    return $this-&gt;getDomainObjectWhere ($select);
}
</pre>

<h2 id="zend_form">Zend_Form</h2>

<p>One of the newest members of the ZF family and definitely one of the most
powerful; <a rel="external" href="http://framework.zend.com/manual/en/zend.form.html">Zend_Form</a> has a steep learning curve, but once setup allows you to create objects capable of gathering, filtering and validating data, as well as rendering the HTML required to display the form.</p>

<p>Forms however tend to be a very personal thing: each developer has their own views on what markup should be used, how fields should be placed and arranged. And since forms come in many different shapes and sizes, they often require logic powering how they are rendered.</p>

<p>Zend_Form is relatively new, and as such the API is very flexible, but it&#8217;s definitely missing pieces (<a rel="external" href="http://akrabat.com/2008/04/07/simple-zend_form-file-upload-example/">file uploads for instance</a>). By it&#8217;s nature it&#8217;s a difficult problem to address, and as such it&#8217;s &#8216;out-of-the-box&#8217;  functionality tends to lean towards the lowest common denominator.</p>

<p>To this extent I nearly always subclass Zend_Form depending on the project to provide some of functionality I need for the particular application. One thing that needs addressing in the short term is a method for quickly rendering hidden elements by themselves without resorting to Display Groups or Sub-Forms.</p>

<h2 id="zend_view">Zend_View</h2>

<p>Most budding PHP developers go through stages. They start off with reasonably simple, self-contained PHP scripts. They then learn to include files and how to make simple templating systems. But eventually they get to the point where a separation of back-end code and display code is needed.</p>

<p>I always thought that PHP itself was high level enough to use as a <em>&#8220;templating language&#8221;</em>. <a rel="external" href="http://www.smarty.net/">Efforts like Smarty</a> mean well, but are constantly forced to justify their existence with arguments like: &#8220;It&#8217;s easier to learn than PHP&#8221; or &#8220;the syntax is simpler and makes more sense to designers&#8221;.</p>

<p>For most modern web developers however layering another language on top of an interpreted scripting language is not a favorable solution. Why not just use plain old vanilla PHP scripts.</p>

<p><a href="http://framework.zend.com/manual/en/zend.view.html" rel="external">Zend_View</a> to the rescue! The simple yet effective use of PHP as a templating engine makes for clean view scripts that really give you the option to abstract HTML and hide any complex logic.</p>

<h2 id="expect_a_lot_more">Expect a lot more!</h2>

<p>This is just a brief look at some pragmatic ways to use ZF in your application. I&#8217;d definitely encourage you to try it out and see how it fits into your development workflow.</p>

<p>In the coming weeks I&#8217;ll be going into some details as to how we&#8217;ve integrated ZF and our own internal code base and specifically how it&#8217;s helping us develop web sites and applications.</p>

]]></description>
      <pubDate>Fri, 18 Apr 2008 04:41:18 +0000</pubDate>
    <feedburner:origLink>http://www.matbyrne.com/2008/4/18/zend-framework-in-practice</feedburner:origLink></item>
  </channel>
</rss>
