<?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>niden.net &#187; Series</title>
	<atom:link href="http://www.niden.net/category/series/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.niden.net</link>
	<description>Boldly goes where no coder has gone before... and other ramblings :)</description>
	<lastBuildDate>Tue, 07 Sep 2010 04:10:36 +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>Design Patterns – Factory [Series][How-To]</title>
		<link>http://www.niden.net/2010/02/design-patterns-factory-series-how-to/</link>
		<comments>http://www.niden.net/2010/02/design-patterns-factory-series-how-to/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 13:55:35 +0000</pubDate>
		<dc:creator>Nikolaos Dimopoulos</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.niden.net/?p=530</guid>
		<description><![CDATA[A note about these series. It appears that Giorgio Sironi and I had the same idea regarding Design Patterns and blogging about them. He covers the Factory design pattern thoroughly in his blog post, which is recommended reading. The Problem I started off my IT career as a network administrator. This was back in the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>A note about these series. It appears that <a href="http://giorgiosironi.blogspot.com">Giorgio Sironi</a> and I had the same idea regarding Design Patterns and blogging about them. He covers the <a href="http://giorgiosironi.blogspot.com/2010/01/practical-php-patterns-factory-method.html">Factory</a> design pattern thoroughly in his blog post, which is recommended reading.</p>
<h3>The Problem</h3>
<p>I started off my IT career as a network administrator. This was back in the good old Novell 3.11 days. After that it was Novell 4.0, Microsoft Servers etc. Following that I got more and more involved with Visual Basic and when Microsoft decided to move everyone to .NET I chose not to follow and ended up coding in PHP.</p>
<p>Since my programming knowledge came from within (studying, reading articles, trial and error), the problems that I was facing on a daily basis are the same as almost every developer faces. One particularly challenging problem that I had in the VB days as well as the PHP days was repetition of code and how to eliminate it.</p>
<p>When I started programming for the <a href="http://ffff.niden.net">Ferrari Fans Fun Forecast</a> site I was running the site using my apartment&#8217;s ADSL line. In the beginning there were only 20 users or so, therefore that setup was fine. The scripts were VBScript against a local instance of Microsoft SQL Server. Later on though, I switched to PHP while keeping Microsoft SQL Server.</p>
<h3>Initial implementation</h3>
<p>I knew that I would have to change my scripts later on to work against MySQL since I was to change the hosting of the site. Through laziness or poor design (you can pick either or both <img src='http://www.niden.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) I chose to create a class for Microsoft SQL and later on I would just change it to the MySQL. It seemed the easiest thing to do at the time.</p>
<p>So my class was something like:</p>
<pre class="brush:php">class DbMSSQL
{
    private $_conn = null;

    public function connect()
    {
         // Connect
        // This is where we have the connection parameters
        include_once 'connection.inc.php';

        $this-&gt;_conn = mssql_connect($host, $user, $password);
        if (!$this-&gt;_conn) {
            throw new Exception('Cannot connect to the database.');
        }
    }

    public function disconnect()
    {
         // Disconnect
        mssql_close($this-&gt;_conn);
    }

    public function selectdb()
    {
         // Select the db
        $db = mssql_select_db($database, $this-&gt;_conn);
        if (!$db) {
            throw new Exception('Cannot select the database');
        }
    }

    public function query($sql)
    {
	    // Query the db
        $_result = mssql_query($sql);

        if (!$_result) {
            throw new Exception('Error in query : ' . $sql);
        }

        $data = array();

        while ($row = mssql_fetch_assoc($_result)) {
            $data[$row['id']] = $row;
        }

        mssql_free_result($_result);

        return $data;
    }
}
?&gt;</pre>
<p>Everything worked fine so I did not worry about a thing. A few months later though I was forced to move the database (as I expected) to MySQL. I could not move everything in one go so I had to move some of the tables initially and a week later everything else.</p>
<p>To tackle this requirement I created a second class to handle operations against MySQL. The class that I ended up with was:</p>
<pre class="brush:php">class DbMySQL
{
    private $_conn = null;

    public function connect()
    {
         // Connect
        // This is where we have the connection parameters
        include_once 'connection.inc.php';

        $this-&gt;_conn = mysql_connect($host, $user, $password);
        if (!$this-&gt;_conn) {
            throw new Exception('Cannot connect to the database :' . mysql_error());
        }
    }

    public function disconnect()
    {
         // Disconnect
        mysql_close($this-&gt;_conn);
    }

    public function selectdb()
    {
         // Select the db
        $db = mysql_select_db($database, $this-&gt;_conn);
        if (!$db) {
            throw new Exception('Cannot select the database : ' . mysql_error());
        }
    }

    public function query($sql)
    {
	    // Query the db
        $_result = mysql_query($sql);

        if (!$_result) {
            throw new Exception('Error in query : ' . mysql_error() . "\n" . $sql);
        }

        $data = array();

        while ($row = mysql_fetch_assoc($_result)) {
            $data[$row['id']] = $row;
        }

        mysql_free_result($_result);

        return $data;
    }
}
?&gt;</pre>
<p>You can easily see the problem here. There is a lot of repetition in the code, not so much as the actual method properties but the methods themselves. Both classes have connect(), disconnect(), selectdb() and query() as methods. In reality the code changes only slightly since the call for an operation against Microsoft SQL Server is <strong>mssql_*</strong> while for MySQL is <strong>mysql_*</strong>. During the transition week I was in programming hell. At some point I mixed the class names, I was trying to read and update the wrong server etc. (see <a href="http://codeutopia.net">Jani Hartikainen</a>&#8216;s post about <a href="http://codeutopia.net/blog/2010/01/28/6-programming-project-mistakes-you-should-avoid/">6 programming project mistakes you should avoid</a> &#8211; I did all that!).</p>
<p>That week though taught me that I need to pay more attention in designing rather than going full speed ahead with programming and later on paying the consequences.</p>
<p>After thorough research, I discovered a library that would support both platforms. The library that I found was <a href="http://adodb.sourceforge.net/">ADOdb</a> which is a perfect example of the Factory Pattern. I used that library later on for a different project, but just looking at the code and understanding the flow of operations as well as the implementation of the pattern itself was invaluable to me.</p>
<p><strong>Interfaces</strong></p>
<p>First of all I need to explain what an interface is and why we need them. According to <a href="http://php.net/manual/en/language.oop5.interfaces.php">PHP.net</a>:</p>
<blockquote><p>Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.</p></blockquote>
<p>So imagine an interface something like a graft, a blueprint on what I need to construct. The Interface will have the common methods and properties that I need to implement.</p>
<p>When dealing with database connections to two different database servers (Microsoft SQL Server and MySQL), I can clearly define a few methods that will follow CRUD (Create, Read, Update, Delete). Those are:</p>
<ol>
<li>Connect to the database server</li>
<li>Select database</li>
<li>Insert record</li>
<li>Delete record</li>
<li>Update record</li>
<li>Select record(s)</li>
<li>Close connection to the database server</li>
</ol>
<p>My interface would therefore be:</p>
<pre class="brush:php">interface iDatabase
{
    public function connect();
    public function disconnect();
    public function selectdb();
    public function query($sql);
}
?&gt;</pre>
<h3>Design Patterns &#8211; Factory</h3>
<p>A class implementing the Factory Pattern is like a car manufacturing plant producing three different cars on the same assembly line. All cars have common characteristics like 4 wheels, 4 doors (well most of them), a steering wheel, a dashboard etc. and all of them perform certain operations i.e. drive, reverse etc.</p>
<p>In my problem earlier I could have used the Factory Pattern to create one class that would have implemented my blueprint, the interface which defines the CRUD operations that I need. So based on the above, the implementation will result in three classes.</p>
<h5>MSSQL class &#8211; stored in the file Db_mssql.php</h5>
<pre class="brush:php">class Db_mssql implements iDatabase
{
    private $_conn = null;

    public function connect()
    {
         // Connect
        // This is where we have the connection parameters
        include_once 'connection.inc.php';

        $this-&gt;_conn = mssql_connect($host, $user, $password);
        if (!$this-&gt;_conn) {
            throw new Exception('Cannot connect to the database.');
        }
    }

    public function disconnect()
    {
         // Disconnect
        mssql_close($this-&gt;_conn);
    }

    public function selectdb()
    {
         // Select the db
        $db = mssql_select_db($database, $this-&gt;_conn);
        if (!$db) {
            throw new Exception('Cannot select the database');
        }
    }

    public function query($sql)
    {
	    // Query the db
        $_result = mssql_query($sql);

        if (!$_result) {
            throw new Exception('Error in query : ' . $sql);
        }

        $data = array();

        while ($row = mssql_fetch_assoc($_result)) {
            $data[$row['id']] = $row;
        }

        mssql_free_result($_result);

        return $data;
    }
}
?&gt;</pre>
<h5>MySQL class &#8211; stored in the file Db_mysql.php</h5>
<pre class="brush:php">class Db_mysql implements iDatabase
{
    private $_conn = null;

    public function connect()
    {
         // Connect
        // This is where we have the connection parameters
        include_once 'connection.inc.php';

        $this-&gt;_conn = mysql_connect($host, $user, $password);
        if (!$this-&gt;_conn) {
            throw new Exception('Cannot connect to the database :' . mysql_error());
        }
    }

    public function disconnect()
    {
         // Disconnect
        mysql_close($this-&gt;_conn);
    }

    public function selectdb()
    {
         // Select the db
        $db = mysql_select_db($database, $this-&gt;_conn);
        if (!$db) {
            throw new Exception('Cannot select the database : ' . mysql_error());
        }
    }

    public function query($sql)
    {
	    // Query the db
        $_result = mysql_query($sql);

        if (!$_result) {
            throw new Exception('Error in query : ' . mysql_error() . "\n" . $sql);
        }

        $data = array();

        while ($row = mysql_fetch_assoc($_result)) {
            $data[$row['id']] = $row;
        }

        mysql_free_result($_result);

        return $data;
    }
}
?&gt;</pre>
<p>Notice that both these classes are almost identical to the initial implementation shown earlier in this post. The only difference is that they are both implementing the iDatabase interface.</p>
<p>So what is different now? The class that implements the Factory Pattern.</p>
<pre class="brush:php">class Db
{
    public static function factory($type)
    {
        $fileName = 'Db_' . strtolower($type) . '.php';
        if (!file_exists($fileName)) {
            throw new Exception('File not found : ' . $fileName);
        }

        $className = 'Db_' . strtolower($type);

        return new $className;
    }
}</pre>
<p>What this class does now is it allows me to load the relevant database connection class on the fly. If I want a Microsoft SQL connection I would call:</p>
<pre class="brush:php">    $mssql = Db::factory('mssql');</pre>
<p>while for MySQL the command becomes:</p>
<pre class="brush:php">    $mysql = Db::factory('mysql');</pre>
<p>Again since both underlying classes implement the iDatabase interface, I know exactly what to expect as far as methods and functionality is concerned from each class.</p>
<h3>Conclusion</h3>
<p>The Factory Design Pattern is one of the most powerful design patterns. It provides &#8216;decoupling&#8217; i.e. breaks the inherited dependency of a class and its subclasses. It also allows for great flexibility while keeping the same interface for your clients.</p>
<p><a href="http://framework.zend.com">Zend Framework</a> uses the Factory Pattern in <a href="http://framework.zend.com/manual/en/zend.db.adapter.html">Zend_Db</a>. Specifically the example on the site shows:</p>
<pre class="brush:php">// We don't need the following statement because the
// Zend_Db_Adapter_Pdo_Mysql file will be loaded for us by
// the Zend_Db factory method.

// require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

// Automatically load class Zend_Db_Adapter_Pdo_Mysql
// and create an instance of it.
$db = Zend_Db::factory('Pdo_Mysql', array(
          'host'     =&gt; '127.0.0.1',
          'username' =&gt; 'webuser',
          'password' =&gt; 'xxxxxxxx',
          'dbname'   =&gt; 'test'
      ));</pre>
<p>The <a href="http://framework.zend.com/manual/en/zend.db.adapter.html">Zend_Db</a> factory accepts the name of the adapter used for the database connection as the first parameter while the second parameter is an array with connection specific information. With the use of the Factory Pattern, <a href="http://framework.zend.com/manual/en/zend.db.adapter.html">Zend_Db</a> exposes a common interface which allows programmers to connect to a number of databases using the same methods. Should in the future the application needs to access a different database, the impact to the developer is minimal &#8211; in most cases a change to the adapter name (first parameter of the factory class) is all it takes.</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6325600846885391";
/* www.niden.net Blog 468x60 */
google_ad_slot = "1288968183";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h4  class="related_post_title">Related Posts</h4><ul class="related_post"><li>January 22, 2010 -- <a href="http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/" title="Design Patterns &#8211; Singleton [Series][How-To]">Design Patterns &#8211; Singleton [Series][How-To]</a> (12)</li><li>January 6, 2010 -- <a href="http://www.niden.net/2010/01/design-patterns-series/" title="Design Patterns &#8211; Series [Series][How-To]">Design Patterns &#8211; Series [Series][How-To]</a> (0)</li><li>December 15, 2009 -- <a href="http://www.niden.net/2009/12/url-beautification/" title="URL Beautification [How-To]">URL Beautification [How-To]</a> (0)</li><li>December 11, 2009 -- <a href="http://www.niden.net/2009/12/variables-in-php-ini/" title="Variables in php.ini [How-To]">Variables in php.ini [How-To]</a> (1)</li><li>November 16, 2009 -- <a href="http://www.niden.net/2009/11/flexible-storage-in-mysql/" title="Flexible Storage in MySQL [How-To]">Flexible Storage in MySQL [How-To]</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.niden.net/2010/02/design-patterns-factory-series-how-to/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Singleton [Series][How-To]</title>
		<link>http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/</link>
		<comments>http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 14:51:22 +0000</pubDate>
		<dc:creator>Nikolaos Dimopoulos</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.niden.net/?p=205</guid>
		<description><![CDATA[A note about these series. It appears that Giorgio Sironi and I had the same idea regarding Design Patterns and blogging about them. He covers the Singleton design pattern thoroughly in his blog post, which is recommended reading. The Problem When I started programming in PHP I was faced with creating a simple database driven [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>A note about these series. It appears that <a href="http://giorgiosironi.blogspot.com">Giorgio Sironi</a> and I had the same idea regarding Design Patterns and blogging about them. He covers the <a href="http://giorgiosironi.blogspot.com/2010/01/practical-php-patterns-singleton.html">Singleton</a> design pattern thoroughly in his blog post, which is recommended reading.</p>
<h3>The Problem</h3>
<p>When I started programming in PHP I was faced with creating a simple database driven web page for a <a href="http://ffff.niden.net">Ferrari Fans Fun club</a>. The page had 5 different sections that each accessed the database to retrieve data. Each section was included in more than one page and only the menu, header and footer were common in all pages.</p>
<p>My first design and implementation was horrible. I still have the files and for the purposes of this blog post I went back and checked on them and I can safely say I am ashamed of that code. But then again we all start from somewhere so that was my start and more importantly I do not program like that any more. The picture below shows how the page was constructed:</p>
<table style="border: 1px solid #4B0082; width: 100%;" border="0">
<tbody>
<tr>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 50px;" colspan="3">Header</td>
</tr>
<tr>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 100px; width: 20%;">Menu</td>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 100px; width: 60%;">Content</td>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 100px; width: 20%;">Additional information</td>
</tr>
<tr>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 50px;" colspan="3">Footer</td>
</tr>
</tbody>
</table>
<p>Each of the sections was a different php script (header.php, menu.php, content.php, footer.php, info.php) and in order to retrieve information from the database for each section I had the following snippet at the top of each script:</p>
<pre class="brush:php">$dbName = 'FFFF';
$dbUser = 'ffff_user';
$dbPass = 'mypassword';
$dbHost = 'localhost';

$conn = mysql_connect($dbHost, $dbUser, $dbPass);
if (!$conn) {
    die(('Cannot connect to the database :' . mysql_error());
}

$db = mysql_select_db($dbName, $conn);
if (!$db) {
    die ('Cannot select the database : ' . mysql_error());
}</pre>
<p>Some might comment on my error handling or the naming of the variables. That is not the problem. The problem is that the snippet of code above was used in <strong>every script file</strong> (all 5 of them). As a result every page load was hitting the database 5 times. Although the intended user base was no more than 100 people, due to this design flaw I had the equivalent of 500 users.</p>
<h3>The first step &#8211; Primitive refactoring</h3>
<p>You might argue that the two files (header, menu) can easily be combined into one (and the same with additional information and footer) and that will save me 3 connections. The layout does not change but now each of the shaded areas represent one script:</p>
<table style="border: 1px solid #4B0082; width: 100%;" border="0">
<tbody>
<tr>
<td style="border: 1px solid #4B0082; background: #DD0000; text-align: center; font-weight: bold; height: 50px;" colspan="3">Header</td>
</tr>
<tr>
<td style="border: 1px solid #4B0082; background: #DD0000; text-align: center; font-weight: bold; height: 100px; width: 20%;">Menu</td>
<td style="border: 1px solid #4B0082; text-align: center; font-weight: bold; height: 100px; width: 60%;">Content</td>
<td style="border: 1px solid #4B0082; background: #00DD00; text-align: center; font-weight: bold; height: 100px; width: 20%;">Additional information</td>
</tr>
<tr>
<td style="border: 1px solid #4B0082; background: #00DD00; text-align: center; font-weight: bold; height: 50px;" colspan="3">Footer</td>
</tr>
</tbody>
</table>
<p>Although this is a good start it is not the solution to the problem. I have effectively reduced the number of hits to 3 per visitor (300 vs 500 before). The goal is to have one connection per visitor.</p>
<h3>One step further &#8211; A global variable</h3>
<p>I need to create the database connection, store it in a global variable, and then let the rest of the scripts access that variable &#8211; and subsequently the database connection &#8211; when needed. The pseudo code is as follows:</p>
<ol>
<li>Load script header.php</li>
<li>Get the database credentials</li>
<li><strong>Create a database connection</strong></li>
<li>Select the database</li>
<li>Display the data</li>
<li>Load script content.php</li>
<li><strong>Get the database connection</strong></li>
<li>Display the data</li>
<li>Load script footer.php</li>
<li><strong>Get the database connection</strong></li>
<li>Display the data</li>
</ol>
<p>I need to ensure that my database connection is initiated at the beginning of every page. The script header.php is the most obvious place:</p>
<pre class="brush:php">$dbName = 'FFFF';
$dbUser = 'ffff_user';
$dbPass = 'mypassword';
$dbHost = 'localhost';

$DBconn = mysql_connect($dbHost, $dbUser, $dbPass);
if (!$DBconn) {
    die(('Cannot connect to the database :' . mysql_error());
}

$db = mysql_select_db($dbName, $DBconn);
if (!$db) {
    die ('Cannot select the database : ' . mysql_error());
}</pre>
<p>In every script thereafter I need to reference the global variable and I can then use it in that script:</p>
<pre class="brush:php">global $DBconn;</pre>
<p>Although this is an &#8220;acceptable&#8221; way of programming, maintaining all the global variables can easily be a nightmare for</p>
<ul>
<li>maintenance</li>
<li>testing</li>
<li>quality control</li>
<li>any part of the code in any script that references this global variable can effectively change that variable</li>
<li>that the code will look &#8220;ugly&#8221; (hey I am proud of the code that I write <img src='http://www.niden.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</li>
</ul>
<h3>Design Patterns &#8211; Singleton</h3>
<p>A better approach to solve this problem is to use a design pattern. In this case I will use the Singleton Pattern.</p>
<p>The Singleton pattern is applied to a class which when called will create a database connection if the connection does not exist or pass the connection back to the caller if it has already been instantiated. This way I really do not care where the database credentials will be added and when the connection will be instantiated. The first time that I am calling the class that implements the Singleton pattern will connect to the database and have the connection stored ready to be used. The pseudo code is as follows:</p>
<ol>
<li>Load script header.php</li>
<li>Get the database credentials</li>
<li><strong>Create a database connection</strong></li>
<li>Select the database</li>
<li>Display the data</li>
<li>Load script content.php</li>
<li><strong>Get the database connection</strong></li>
<li>Display the data</li>
<li>Load script footer.php</li>
<li><strong>Get the database connection</strong></li>
<li>Display the data</li>
</ol>
<p>The class that I created is as follows:</p>
<pre class="brush:php">&lt;?php
class Db
{
    private static $_db   = null;
    private static $_conn = null;

    private function __construct()
    {
        // This is where we have the connection parameters
        include_once 'connection.inc.php';

        $this-&gt;_conn = mysql_connect($host, $user, $password);
        if (!$this-&gt;_conn) {
            throw new Exception('Cannot connect to the database :' . mysql_error());
        }

        $db = mysql_select_db($database, $this-&gt;_conn);
        if (!$db) {
            throw new Exception('Cannot select the database : ' . mysql_error());
        }
    }

    private function __destruct()
    {
        mysql_close($this-&gt;_conn);
    }

    // The singleton method
    public static function getInstance()
    {
        if (null === self::$db) {
            self::$_db = new Db($options);
        }

        return self::$_db;
    }

    public function query($sql)
    {
        $_result = mysql_query($sql);

        if (!$_result) {
            throw new Exception('Error in query : ' . mysql_error() . "\n" . $sql);
        }

        $data = array();

        while ($row = mysql_fetch_assoc($_result)) {
            $data[$row['id']] = $row;
        }

        mysql_free_result($_result);

        return $data;
    }
}
?&gt;</pre>
<p>With this class available I really do not care if my database connection code is at the beginning of my scripts or not. Using this class allows me to create the database connection (if it is not established) and persist/reuse it further down the script execution.</p>
<p>The code for my header and menu (see graphic above) becomes:</p>
<pre class="brush:php">    $sql = 'SELECT menu_id, menu_name FROM tbl_menu';
    $menu = Db::getInstance()-&gt;query($sql);</pre>
<p>while the one for the rest of the site is exactly identical sans the query to be executed. The problem is solved (I now have one connection per visitor) and the code seems a lot tidier.</p>
<p>Note that the connection parameters are in a separate file which is accessed during the __construct() method of the class. You can use anything you want to supply these parameters in your class.</p>
<h3>Conclusion</h3>
<p>The Singleton Design Pattern is a blessing in disguise. If the ground work has not been done (i.e. create tests for your code and thoroughly document it) then it is difficult for a new developer coming into a project to understand what is going on, especially when the new developer needs to make alterations and run newly created tests.</p>
<p>A word of caution: If you choose to use this pattern in your application, make sure that everything you do is thoroughly documented and tested. This will make your life a lot easier in the long run and will aid in maintenance.</p>
<h5>Update: Thanks to <a rel="external nofollow" href="http://codeutopia.net/">Jani Hartikainen</a> for pointing out an error in the code.</h5>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6325600846885391";
/* www.niden.net Blog 468x60 */
google_ad_slot = "1288968183";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h4  class="related_post_title">Related Posts</h4><ul class="related_post"><li>February 2, 2010 -- <a href="http://www.niden.net/2010/02/design-patterns-factory-series-how-to/" title="Design Patterns – Factory [Series][How-To]">Design Patterns – Factory [Series][How-To]</a> (0)</li><li>January 6, 2010 -- <a href="http://www.niden.net/2010/01/design-patterns-series/" title="Design Patterns &#8211; Series [Series][How-To]">Design Patterns &#8211; Series [Series][How-To]</a> (0)</li><li>December 15, 2009 -- <a href="http://www.niden.net/2009/12/url-beautification/" title="URL Beautification [How-To]">URL Beautification [How-To]</a> (0)</li><li>December 11, 2009 -- <a href="http://www.niden.net/2009/12/variables-in-php-ini/" title="Variables in php.ini [How-To]">Variables in php.ini [How-To]</a> (1)</li><li>November 16, 2009 -- <a href="http://www.niden.net/2009/11/flexible-storage-in-mysql/" title="Flexible Storage in MySQL [How-To]">Flexible Storage in MySQL [How-To]</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Design Patterns &#8211; Series [Series][How-To]</title>
		<link>http://www.niden.net/2010/01/design-patterns-series/</link>
		<comments>http://www.niden.net/2010/01/design-patterns-series/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 19:52:47 +0000</pubDate>
		<dc:creator>Nikolaos Dimopoulos</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Series]]></category>

		<guid isPermaLink="false">http://www.niden.net/?p=202</guid>
		<description><![CDATA[A lot of developers – including myself – have at some point in their programming careers found themselves repeating a task that they have completed for a previous project or for a previous part of the same project. This problem of repeating code is solved by design patterns. A design pattern is the way that [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>A lot of developers – including myself – have at some point in their programming careers found themselves repeating a task that they have completed for a previous project or for a previous part of the same project.</p>
<p>This problem of repeating code is solved by design patterns. A design pattern is the way that the code must be structured so that the problem at hand can be solved. The characteristics of design patterns are:</p>
<ul>
<li><strong>Name</strong> – it lets other programmers know what this pattern does.</li>
<li><strong>Problem</strong> – where the pattern can be applied</li>
<li><strong>Solution</strong> – how this pattern is implemented</li>
</ul>
<p>In the course of the next few weeks, I will publish a series of blog posts, where  I will try to present you with some common design patterns and how I have understood their use. Most books and online materials concentrate on just presenting the issue at hand and do not focus on how we ended up there. In these blog post series I will try to show you what I found along the way and how I solved each problem in turn.</p>
<p>As usual comments are more than welcome.</p>
<p>The design patterns I will discuss in posts of these series are as:</p>
<ol>
<li><a href="http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/">Singleton Pattern</a></li>
<li><a href="http://www.niden.net/2010/01/design-patterns-factory-series-how-to/">Factory Pattern</a></li>
<li>Registry Pattern</li>
<li>Decorator Pattern</li>
<li>Adapter Pattern</li>
<li>Iterator Pattern</li>
<li>Strategy Pattern</li>
<li>Active Record Pattern</li>
<li>Value Object Pattern</li>
<li>Model View Controller Pattern</li>
<li>MockObject Pattern</li>
<li>Observer Pattern</li>
<li>Proxy Pattern</li>
<li>Table Data Gateway Pattern</li>
<li>Data Mapper Pattern</li>
</ol>
<p>You can check this blog every week, <a href="http://feeds.feedburner.com/nikosdimopoulos">subscribe to the RSS feed</a>, <a href="http://twitter.com/nikosdimopoulos">follow me on Twitter</a> or <a href="http://www.google.com/profiles/nikos.dimopoulos.usa">follow my Google Reader</a> (or all of the above).</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6325600846885391";
/* www.niden.net Blog 468x60 */
google_ad_slot = "1288968183";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h4  class="related_post_title">Related Posts</h4><ul class="related_post"><li>February 2, 2010 -- <a href="http://www.niden.net/2010/02/design-patterns-factory-series-how-to/" title="Design Patterns – Factory [Series][How-To]">Design Patterns – Factory [Series][How-To]</a> (0)</li><li>January 22, 2010 -- <a href="http://www.niden.net/2010/01/design-patterns-singleton-series-how-to/" title="Design Patterns &#8211; Singleton [Series][How-To]">Design Patterns &#8211; Singleton [Series][How-To]</a> (12)</li><li>December 15, 2009 -- <a href="http://www.niden.net/2009/12/url-beautification/" title="URL Beautification [How-To]">URL Beautification [How-To]</a> (0)</li><li>December 11, 2009 -- <a href="http://www.niden.net/2009/12/variables-in-php-ini/" title="Variables in php.ini [How-To]">Variables in php.ini [How-To]</a> (1)</li><li>December 2, 2009 -- <a href="http://www.niden.net/2009/12/the-world-with-angular-part-3/" title="The world with &lt;angular/&gt; Part 3 [Review][How-To]">The world with &lt;angular/&gt; Part 3 [Review][How-To]</a> (1)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.niden.net/2010/01/design-patterns-series/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
