<?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>Mark Young&#039;s Blog</title>
	<atom:link href="http://www.sparky-san.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sparky-san.com</link>
	<description>Web Development Discussion (Focusing on PHP, MySQL and whatever else grabs my interest at the time)</description>
	<lastBuildDate>Mon, 20 Jun 2011 22:23:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Rendering issues in Sencha Touch caused by Ext.Sheet</title>
		<link>http://www.sparky-san.com/rendering-issues-sencha-touch-caused-ext-sheet/</link>
		<comments>http://www.sparky-san.com/rendering-issues-sencha-touch-caused-ext-sheet/#comments</comments>
		<pubDate>Mon, 20 Jun 2011 22:23:01 +0000</pubDate>
		<dc:creator>Mark Young</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Sencha Touch]]></category>

		<guid isPermaLink="false">http://www.sparky-san.com/?p=636</guid>
		<description><![CDATA[I&#8217;ve spent quite a bit of time dealing with what appears to be a fairly serious problem in Sencha&#8217;s mobile device framework. Whilst it is an incredibly powerful and flexible framework there are some bugs in it&#8217;s core that need &#8230; <a href="http://www.sparky-san.com/rendering-issues-sencha-touch-caused-ext-sheet/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent quite a bit of time dealing with what appears to be a fairly serious problem in Sencha&#8217;s mobile device framework. Whilst it is an incredibly powerful and flexible framework there are some bugs in it&#8217;s core that need addressing before it will work properly for your application.<br />
<span id="more-636"></span></p>
<p>The bug I am referring to is caused by most elements that extend the Ext.Sheet component in the framework. This includes select fields, action sheets and date pickers. Once an Ext.Sheet based component has been rendered once the layout will render incorrectly on orientation change. This is a fairly serious issue as it the only way to resolve it at that point is to reload the application.</p>
<p>The problem can be fixed by overriding three different methods as follows:</p>
<pre class="brush: jscript; title: ; notranslate">
Ext.override(Ext.Sheet, {
    doHide: function(el, options){
        var parent = this.el.parent();

        this.el.hide();

        if (parent &amp;&amp; this.floating &amp;&amp; this.modal) {
            parent.unmask();
        }
        if (options &amp;&amp; options.fireHideEvent) {
            this.fireEvent('hide', this);
        }

        if (Ext.isObject(el)) {
            if (!(this instanceof Ext.MessageBox)) {
	           this.destroy();
            }
    	}
    }
});

Ext.override(Ext.form.Select, {

    getPicker: function() {
        if (this.picker) {
            this.picker.destroy();
            this.picker = null;
        }
        this.picker = new Ext.Picker({
            slots: [{
                align       : 'center',
                name        : this.name,
                valueField  : this.valueField,
                displayField: this.displayField,
                value       : this.getValue(),
                store       : this.store
            }],
            listeners: {
                change: this.onPickerChange,
                scope: this
            }
        });

        return this.picker;
    }

});

Ext.override(Ext.form.DatePicker, {
    onPickerHide: function(){
        if (this.datePicker){
            this.datePicker.destroy();
            this.datePicker = null;
        }
    }
});
</pre>
<p>The first of these fixes is courtesy of the sencha touch forum user <a href="http://www.sencha.com/forum/member.php?126809-gcallaghan" title="gcallaghan">gcallaghan</a>. Each of these overrides essentially ensures that the instance of the relevent picker is destroyed instead of hidden.</p>
<p>The overhead incurred by recreating the picker/sheet each time is minimal thanks to the speed at which most of the major mobile browsers can manipulate the dom. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.sparky-san.com/rendering-issues-sencha-touch-caused-ext-sheet/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Efficient and convenient autoloading in PHP</title>
		<link>http://www.sparky-san.com/efficient-convenient-autoloading-php/</link>
		<comments>http://www.sparky-san.com/efficient-convenient-autoloading-php/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 22:36:20 +0000</pubDate>
		<dc:creator>Mark Young</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://fang/blog/?p=597</guid>
		<description><![CDATA[PHP5 introduced the concept of auto loading to PHP. Although this new ability saves developers the nightmare of including every class file they need explicitly at the top of each file, the default implementation is somewhat limited. You can get &#8230; <a href="http://www.sparky-san.com/efficient-convenient-autoloading-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>PHP5 introduced the concept of auto loading to PHP. Although this new ability saves developers the nightmare of including every class file they need explicitly at the top of each file, the default implementation is somewhat limited. You can get the best out of this functionality by writing your own autoload method.</p>
<p><span id="more-597"></span></p>
<p>The inbuilt autoload function provided by PHP is restrictive. It searches through the defined <code>include_path</code> and if the appropriate file is not found in that directory it throws an error. When you are applying an OOP approach to the development of a system you often end up with a lot of class files. Having all these files in one directory is not a particularly attractive prospect for anyone who likes to keep their code organised. </p>
<p>We can deal with this limitation by providing PHP with a custom autoload function that is capable of scanning particular directories in a recursive manor. This will allow us to organise our code as we see fit. Below is the typical structure I would use for the class files of a website or app I was building:</p>
<p><img src="http://www.sparky-san.com/wp-content/uploads/2011/03/app_structure.gif" alt="Typical Application Class Structure" title="Typical Application Class Structure" width="253" height="254" class="alignnone size-full wp-image-602" /></p>
<p>As you can see the autoload function we need to build must be capable of scanning recursively through all directories within the &#8220;inc&#8221; directory. Of course, searching through all these directories every time a request is made for a class file would be extremely inefficient. The solution for this is to have the autoloader also maintain a path cache for the class files. This way, when a class is found it can save the full path to the cache and the next time it is requested the search will not be necessary.</p>
<p>Below is the full code for the autoload function we can use to achieve this goal:</p>
<pre class="brush: php; title: ; notranslate">
function application_autoloader($class) {
	$class = strtolower($class);
	$class_filename = 'class.'.strtolower($class).'.php';
	$class_root = dirname(__FILE__);
	$cache_file = &quot;{$class_root}/cache/classpaths.cache&quot;;
	$path_cache = (file_exists($cache_file)) ? unserialize(file_get_contents($cache_file)) : array();
	if (!is_array($path_cache)) { $path_cache = array(); }

	if (array_key_exists($class, $path_cache)) {
		/* Load class using path from cache file (if the file still exists) */
		if (file_exists($path_cache[$class])) { require_once $path_cache[$class]; }

	} else {
		/* Determine the location of the file within the $class_root and, if found, load and cache it */
		$directories = new RecursiveDirectoryIterator($class_root);
		foreach(new RecursiveIteratorIterator($directories) as $file) {
			if (strtolower($file-&gt;getFilename()) == $class_filename) {
				$full_path = $file-&gt;getRealPath();
				$path_cache[$class] = $full_path;
				require_once $full_path;
				break;
			}
		}	

	}

	$serialized_paths = serialize($path_cache);
	if ($serialized_paths != $path_cache) { file_put_contents($cache_file, $serialized_paths); }
}

spl_autoload_register('application_autoloader');
</pre>
<p>Before we break this code down to understand more fully what it is doing we should note that this function is located in the &#8220;app.intiailise.php&#8221; file in the directory structure we looked at earlier. The reason for this is simple. It means we don&#8217;t need to explicitly specify the path we wish to use as the class root, we can simply look at the directory the file is in using <code>dirname(__FILE__)</code>.  Let&#8217;s look at the code in a bit more detail.</p>
<pre class="brush: php; title: ; notranslate">
	$class = strtolower($class);
	$class_filename = 'class.'.strtolower($class).'.php';
	$class_root = dirname(__FILE__);
</pre>
<p>The function begins by ensuring that the name of the class being called is in lowercase (to ensure no issues with case sensitive operating systems). We then go on to establish that the file we are looking for is called &#8220;class.<em>classname</em>.php&#8221;. The filename format is dictated by personal preference, it could just as easily be &#8220;<em>classname</em>.php&#8221; or &#8220;<em>classname</em>.class.php&#8221; if you change it. The key point to make here is that it must be consistent so the autoloader knows what to look for. Finally we determine the root directory for all the class files which happens to be the location in which this file resides.</p>
<pre class="brush: php; title: ; notranslate">
	$cache_file = &quot;{$class_root}/cache/classpaths.cache&quot;;
	$path_cache = (file_exists($cache_file)) ? unserialize(file_get_contents($cache_file)) : array();
	if (!is_array($path_cache)) { $path_cache = array(); }
</pre>
<p>Next we focus on initialising the class path cache. The file is held in the cache directory (which is in the same directory as &#8220;app.intiialise.php&#8221;. The cache itself is held as a serialized array. This means it can easily be saved as a string in a file and converted back into an array again. The code simply fetches the contents of the cache file and unserializes it. There is some work to ensure that the <code>$path_cache</code> variable always holds an array but this should never be the case, it&#8217;s just a healthy dose of paranoia.</p>
<pre class="brush: php; title: ; notranslate">
	if (array_key_exists($class, $path_cache)) {
		/* Load class using path from cache file (if the file still exists) */
		if (file_exists($path_cache[$class])) { require_once $path_cache[$class]; }

	} else {
		/* Determine the location of the file within the $class_root and, if found, load and cache it */
		$directories = new RecursiveDirectoryIterator($class_root);
		foreach(new RecursiveIteratorIterator($directories) as $file) {
			if (strtolower($file-&gt;getFilename()) == $class_filename) {
				$full_path = $file-&gt;getRealPath();
				$path_cache[$class] = $full_path;
				require_once $full_path;
				break;
			}
		}	

	}

	$serialized_paths = serialize($path_cache);
	if ($serialized_paths != $path_cache) { file_put_contents($cache_file, $serialized_paths); }
</pre>
<p>This is the meat of the function. We check the <code>$path_cache</code> to check if the file that is being requested has previously been located. If it has we can simply use the path stored in the array to require the file. </p>
<p>If no entry is found in the cache the function goes on to scan the child directories for the requested file. We achieve this by making use of PHP&#8217;s inbuilt <a href="http://www.php.net/manual/en/class.recursivedirectoryiterator.php" title="RecursiveDirectoryIterator Class">RecursiveDirectoryIterator</a> and <a href="http://www.php.net/manual/en/class.recursiveiteratoriterator.php" title="RecursiveIteratorIterator">RecursiveIteratorIterator</a> classes. </p>
<p>The combinatation of these classes yields a collection of <a href="http://www.php.net/manual/en/class.splfileinfo.php" title="SPLFileInfo Class">SPLFileInfo</a> objects which contain details of all the files below the root. Once a match is found for the file that is requested we simply save it to the cache array and require the file. Finally we serialize the path cache once more and save it to the cache file only if changes have been made (this saves a little bit of unnecessary work).</p>
<p>Now that we have created our function we need to tell PHP to use it to autoload the files. We do this like so:</p>
<pre class="brush: php; title: ; notranslate">
spl_autoload_register('application_autoloader');
</pre>
<p>The reason we do this instead of just overwriting PHP&#8217;s autoload function using <code>__autoload</code> is because <code>spl_autoload_register</code> allows us to stack autoloaders. This means that it will execute each of the autoloaders added to the stack in turn, newest first. If the first fails, it will move on to the second and so on until the stack is exhausted at which point PHP throws an error.</p>
<p>Using this method of autoloading requires that you keep the following things in mind when creating a new class file:</p>
<ul>
<li>You must maintain a one class per file policy.</li>
<li>All your class files must be named with the same structure e.g. &#8220;class.classname.php&#8221;.</li>
</ul>
<p>Some last thoughts; you could make this function slightly more efficient still by storing the unserialized cache array in a global store so that it does not need to access the file with each run. There are undoubtedly other optimisations we could make here but I think this is a pretty good starting point.</p>
<p>I have created a simple demo of this concept which you can download and run on your own webserver to try it out yourself. You can <a href="http://www.sparky-san.com/wp-content/uploads/2011/03/autoloader.zip" title="Download the Autoloader">download it here</a>. One important thing to note before running the demo; make the &#8220;cache&#8221; folder writeable by your webserver otherwise it will be unable to create the class path cache. Let me know your thoughts!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sparky-san.com/efficient-convenient-autoloading-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Design, New Start!</title>
		<link>http://www.sparky-san.com/new-design-new-start/</link>
		<comments>http://www.sparky-san.com/new-design-new-start/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 16:56:44 +0000</pubDate>
		<dc:creator>Mark Young</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://fang/blog/?p=590</guid>
		<description><![CDATA[So&#8230; yeah, I clearly didn&#8217;t do much in the way of keeping this blog updated since it&#8217;s inception. I have, however, promised myself to make a new start on it. As you can see I have redesigned the entire website &#8230; <a href="http://www.sparky-san.com/new-design-new-start/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So&#8230; yeah, I clearly didn&#8217;t do much in the way of keeping this blog updated since it&#8217;s inception. I have, however, promised myself to make a new start on it. As you can see I have redesigned the entire website and hopefully it&#8217;s a lot less cluttered and a lot more accessible. </p>
<p><span id="more-590"></span></p>
<p>If you have any comments, problems or queries about the new design or anything else feel free to <a href="http://www.sparky-san.com/contact/" title="Contact Me">get in touch with me</a>. </p>
<p>At the moment I am working through a number of different development, project management and usability books and in coming months you should see a lot of posts here as I talk about my thoughts on these subjects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sparky-san.com/new-design-new-start/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Design Patterns: Strategy Pattern</title>
		<link>http://www.sparky-san.com/php-design-patterns-strategy-pattern/</link>
		<comments>http://www.sparky-san.com/php-design-patterns-strategy-pattern/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 22:25:32 +0000</pubDate>
		<dc:creator>Mark Young</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://fang/blog/?p=560</guid>
		<description><![CDATA[I have recently finished reading Matt Zandstra&#8217;s PHP5 Objects, Patterns and Practice. With PHP5&#8242;s much improved support for object oriented coding, tried and tested design patterns have become much more applicable to PHP development. I will be looking at a &#8230; <a href="http://www.sparky-san.com/php-design-patterns-strategy-pattern/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have recently finished reading Matt Zandstra&#8217;s <a title="PHP5 Objects, Patterns and Practice" href="http://www.amazon.co.uk/PHP-5-Objects-Patterns-Practice/dp/1590593804/">PHP5 Objects, Patterns and Practice</a>. With PHP5&#8242;s much improved support for object oriented coding, tried and tested design patterns have become much more applicable to PHP development.</p>
<p><span id="more-560"></span></p>
<p>I will be looking at a number of design patterns of the coming months but for this post we will focus on the strategy pattern. The strategy pattern employs the principles of <a title="Polymorphism" href="http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming">polymorphism</a> to help prevent recurring conditionals throughout your code.</p>
<p>I find these patterns are best demonstrated with examples so we will imagine we are developing a system that manages the billing of project work. One of the most common tasks a system like this will be required to carry out is calculate the total price of a project. </p>
<p>If we look at a poorly thought out implementation of this pricing logic we would probably see the following section of code repeated several times throughout the system.</p>
<pre class="brush: php; title: ; notranslate">
switch ($project-&gt;charge_type) {
    case 'fixed_price':
        $price = $project-&gt;fixed_price;
    break;
    case 'hourly_rate':
        $price = $total_hours * $hourly_rate;
    break;
}
</pre>
<p>Conditionals that are replicated many times throughout a system are a typical example of what is known as a <a title="Code Smell" href="http://en.wikipedia.org/wiki/Code_smell">code smell</a>. Such code smells are a good indication that you need to re-factor your code. This is where the Strategy pattern comes into play.</p>
<p>The strategy pattern attempts to circumvent one of the most common problems with object oriented systems; the object that knew too much. By separating and encapsulating individual responsibilities within other classes we can keep our objects focused on managing their own section of logic. </p>
<p>A project object, for example, should be concentrating on managing data specific to a project. If we give it responsibility for managing the pricing structures as well then we are starting to increase both the likeliness of bugs and the difficulty of maintenance. The strategy pattern can be used here to separate the pricing logic from the core project object like so:</p>
<pre class="brush: php; title: ; notranslate">
interface PricingStrategy {
    function price() {}
}

abstract class PriceStrategy implements PricingStrategy {
    function __construct() {}
    function price() {}
}

class FixedPriceStrategy extends PriceStrategy {
    function price() {
        return $fixed_rate_price;
    }
}

class HourlyPriceStrategy extends PriceStrategy {
    function price() {
        return $hours * $hourly_rate;
    }
}

class Project {
   public $pricing_structure;

    function __construct(PriceStrategy $pricing_strategy) {
        $this-&gt;pricing_structure = $pricing_strategy;
    }
}
</pre>
<p>By implementing the PricingStrategy interface each of the pricing objects guarantees support for the price function. As a result the main project object can hold a reference to any of these and call the price function knowing that it will be supported. Now instead of having messy conditionals littered throughout the code a project object can be instantiated by passing any of the chosen pricing structure objects to it&#8217;s constructor as follows:</p>
<pre class="brush: php; title: ; notranslate">
$project = new Project(new FixedPriceStrategy());

echo 'The cost of this project is: '.$project-&gt;pricing_structure-&gt;Price();
</pre>
<p>This is of course a very crude and stripped down example but none the less it should demonstrate some of the benefits to this pattern. </p>
<ul>
<li>Minimising the replication of conditionals through code will reduce the chances of encountering bugs and make maintenance simpler.</li>
<li>The design results in simplified client coding meaning other members of the team can easily implement your code in other parts of the system without having to know the inner working of the pricing logic.</li>
<li>Addition of new pricing strategies becomes a simple matter of adding a new class. Meaning new pricing structures can be integrated more quickly and reliably.</li>
</ul>
<p>If you want to learn more then the following links will provide you with some more reading:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Strategy_pattern" title="Wikipedia's Strategy Pattern page">Wikipedia&#8217;s Strategy Pattern page</a></li>
<li><a href="http://www.ibm.com/developerworks/library/os-php-designptrns/#N1022F" title="Five Common PHP Design Patterns">Five Common PHP Design Patterns</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.sparky-san.com/php-design-patterns-strategy-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hello world!</title>
		<link>http://www.sparky-san.com/hello-world/</link>
		<comments>http://www.sparky-san.com/hello-world/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 18:34:24 +0000</pubDate>
		<dc:creator>Mark Young</dc:creator>
				<category><![CDATA[General Stuff]]></category>

		<guid isPermaLink="false">http://localhost/blog/?p=1</guid>
		<description><![CDATA[A big hello! What should a first post consist of? Well, to avoid it becoming an onslaught of waffle I will focus on answering 3 questions&#0133; Who are you? My name is Mark Young, I&#8217;m a 28 year old web &#8230; <a href="http://www.sparky-san.com/hello-world/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A big hello! What should a first post consist of? Well, to avoid it becoming an onslaught of waffle I will focus on answering 3 questions&#0133;</p>
<p><span id="more-1"></span><br />
<strong>Who are you?</strong></p>
<p>My name is Mark Young, I&#8217;m a 28 year old web developer who also dabbles in design. I live in a town called St. Helens in England which is roughly between Liverpool and Manchester. For those of you that have the time or inclination you can <a title="Learn more about Me!" href="/about/">learn more about me here</a>.</p>
<p><strong>What will you be blogging about?</strong></p>
<p>Well, my area of choice will, for the most part, revolve around web development and design. In terms of development I focus mostly on PHP and MySQL, however, along with front-end development topics like HTML5 and CSS3 I will also touch on some of my other areas of interest (including iPhone development, mobile web apps and heuristics).</p>
<p><strong>What is the reason you are blogging?</strong></p>
<p>I was hesitant for the longest of times to start my own blog because I felt it was a mite narcissistic. What can I offer that isn&#8217;t already available on the seemingly infinite number of existing blogs on the same topics? I asked myself.</p>
<p>As time passed I realised that perhaps it could be viewed as more of an exercise in my own personal and professional development. As I work to improve my own skills I can keep track of and discuss them here; Think of this as my own little sandbox. Although I profess to be no master of my craft perhaps anyone reading can learn something through my own experiences at the same time.</p>
<p>As with most blogs you are of course invited to comment on any posts I make using the comment functionality found at the bottom of any article. All friendly discussion and constructive criticism are warmly welcomed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sparky-san.com/hello-world/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

