• 2010-02-02 12:00:00

    Design Patterns - Factory

    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 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.

    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.

    When I started programming for the Ferrari Fans Fun Forecast site I was running the site using my apartment'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.

    Initial implementation

    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 :)) 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.

    So my class was something like:

     class DbMSSQL
    {
        private $_conn = null;
    
        public function connect()
        {
            // Connect
            // This is where we have the connection parameters
            include_once 'connection.inc.php';
    
            $this->_conn = mssql_connect($host, $user, $password);
            if (!$this->_conn) {
                throw new Exception('Cannot connect to the database.');
            }
        }
    
        public function disconnect()
        {
             // Disconnect
            mssql_close($this->_conn);
        }
    
        public function selectdb()
        {
             // Select the db
            $db = mssql_select_db($database, $this->_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;
        }
    }
    

    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.

    To tackle this requirement I created a second class to handle operations against MySQL. The class that I ended up with was:

    class DbMySQL
    {
        private $_conn = null;
    
        public function connect()
        {
            // Connect
            // This is where we have the connection parameters
            include_once 'connection.inc.php';
    
            $this->_conn = mysql_connect($host, $user, $password);
            if (!$this->_conn) {
                throw new Exception('Cannot connect to the database :' . mysql_error());
            }
        }
    
        public function disconnect()
        {
             // Disconnect
            mysql_close($this->_conn);
        }
    
        public function selectdb()
        {
             // Select the db
            $db = mysql_select_db($database, $this->_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;
        }
    }
    

    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 mssql_* while for MySQL is mysql_*. 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 Jani Hartikainen's post about 6 programming project mistakes you should avoid - I did all that!).

    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.

    After thorough research, I discovered a library that would support both platforms. The library that I found was ADOdb 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.

    Interfaces

    First of all I need to explain what an interface is and why we need them. According to PHP.net:

    Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

    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.

    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:

    • Connect to the database server
    • Select database
    • Insert record
    • Delete record
    • Update record
    • Select record(s)
    • Close connection to the database server

    My interface would therefore be:

    interface iDatabase
    {
        public function connect();
        public function disconnect();
        public function selectdb();
        public function query($sql);
    }
    

    Design Patterns - Factory

    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.

    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.

    MSSQL class - stored in the file Db_mssql.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->_conn = mssql_connect($host, $user, $password);
            if (!$this->_conn) {
                throw new Exception('Cannot connect to the database.');
            }
        }
    
        public function disconnect()
        {
             // Disconnect
            mssql_close($this->_conn);
        }
    
        public function selectdb()
        {
             // Select the db
            $db = mssql_select_db($database, $this->_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;
        }
    }
    
    MySQL class - stored in the file Db_mysql.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->_conn = mysql_connect($host, $user, $password);
            if (!$this->_conn) {
                throw new Exception('Cannot connect to the database :' . mysql_error());
            }
        }
    
        public function disconnect()
        {
             // Disconnect
            mysql_close($this->_conn);
        }
    
        public function selectdb()
        {
             // Select the db
            $db = mysql_select_db($database, $this->_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;
        }
    }
    

    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.

    So what is different now? The class that implements the Factory Pattern.

    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;
        }
    }
    

    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:

        $mssql = Db::factory('mssql');
    

    while for MySQL the command becomes:

        $mysql = Db::factory('mysql');
    

    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.

    Conclusion

    The Factory Design Pattern is one of the most powerful design patterns. It provides 'decoupling' 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.

    Zend Framework uses the Factory Pattern in Zend_Db. Specifically the example on the site shows:

    // 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'     => '127.0.0.1',
            'username' => 'webuser',
            'password' => 'xxxxxxxx',
            'dbname'   => 'test'
        )
    );
    

    The Zend_Db 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, Zend_Db 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 - in most cases a change to the adapter name (first parameter of the factory class) is all it takes.

  • 2010-01-22 12:00:00

    Design Patterns - Singleton

  • 2009-12-15 12:00:00

    URL beautification in PHP

    Preface

    The last few years I have been using Quicken to manage the home bank accounts and spending. My wife never had any problems with me doing so and it helps us manage our cash flow better. Of course like every couple we buy things that we need and always provision a small amount of money for personal expenses.

    Some time ago when downloading the transactions from our bank, I noticed a rather odd name coming in for a very small charge (less than 20 dollars). So I asked my wife what that shop is. Her response was Beautification. My reply was What do you mean? You don't need anything - you are gorgeous as is.... Although this did earn me brownie points it also infuriated my wife since she was thinking I was auditing her. My sole purpose of that question was to assess the category of the expense and move on. I was not interested the least about the particulars of the expense. I got my reply - a detailed one - as to what the item was for (makeup really) and once my wife finished I explained to her that all this explanation was unnecessary and all I needed was Personal Care.... The night ended in laughter as you can imagine and since then we always refer as Beautification when we pass the makeup area in the grocery store.

    The purpose of this post is not to try to make you go buy makeup. It is however a post that can show you how you can make your application's behavior as far as URLs are concerned prettier.

    Beautification in URLs is also known as Pretty URLs. It is a method where mod_rewrite is used to make a URL look easier to remember. Although this process started in an attempt to increase SEO and make a site's URLs easier to index/follow, it has now become a must for every site that wants to create awareness and make people remember as much as possible so that they can revisit. Wordpress (this blog's blogging software) as well as other blogging software use this methodology to ensure that the posts are easily indexed and remembered (see the URL of this post and the title of this post).

    Beautification

    First Step

    Instead of rewriting my whole application to have beautiful and easy to remember URLs, I started with changing the way I processed parameters. Imagine the scenario where I have a site with various pages and one script that processes everything. My URL could be something like:

    ..../site.php?page=contact-us
    ..../site.php?page=about
    

    Following discussions with other developers and reading the web the URL was beautified as:

    ..../site.php?page/contact-us
    ..../site.php?page/about
    

    This is one parameter, so in my bootstrap I have the following snippet:

    $getData      = array();
    $params       = explode('/',$_SERVER['QUERY_STRING']);
    $params[]     = '';
    $paramsLength = sizeof($params);
    
    for ($counter = 0; $counter < $paramsLength; $counter++) {
        $getData[$params[$counter]] = (isset($params[$counter + 1])) ? $params[$counter + 1] : '';
    }
    
    unset($_GET);
    

    The $getData array contains the parameters that have been passed and allows all search engines to index the URL a lot easier since this is considered to be one parameter.

    Please note that I am not going to expand on security here. In my production code there are multiple checks on the variables passed so as to ensure that there are no SQL injection vulnerabilities.

    A better approach with .htaccess

    In order to make the URL look a lot more beautified, I need to remove the script name and the question mark of the query string. So my URL can easily be like:

    ..../page/contact-us
    ..../page/about</pre>
    

    To achieve this, I need (in Apache) modrewrite enabled and a couple of directives in httpd.conf

    Options +FollowSymLinks
    RewriteEngine On
    

    If your configuration is on a virtual host, you can add these directives in your vhosts file.

    The .htaccess file that I have in the root folder of my site has the following directives:

    Options       +FollowSymLinks
    RewriteEngine On
    RewriteCond   %{SCRIPT_FILENAME} !-d
    RewriteCond   %{SCRIPT_FILENAME} !-f
    RewriteRule   .* site.php [L]</pre>
    

    What the above file does is pass everything in the site.php script. The processing now falls in the site.php script. At the top of the script I have:

    <?php
    
    // This is where we get all the parameters
    $params = $_SERVER['REQUEST_URI'];
    
    if (substr('/', $params) > 0) {
        switch ($params) {
            case '/page/contact-us':
                include 'contact_us.php';
                break;
            case '/page/about':
                include 'about.php';
                break;
            default:
                include 'filenotfound.php';
                break;
        }
    
    // No parameters passed - display something default
    } else {
       include 'filenotfound.php';
    }
    

    From here on the possibilities are endless. I can add more logic to the rewrite rules so that everything ends in .html for instance, making search engines think that they are visiting unique html pages. Discussion forum software uses this technique to make their content easily searchable. For instance a URL like:

    /showpost.php?p=557799
    

    can be shown as:

    /show/post/post/557799
    

    or

    /show/post/post-557799.html
    

    Something like the above can be achieved with the following rule in .htaccess:

    Options       +FollowSymLinks
    RewriteEngine On
    RewriteRule   ^post-([0-9]+)+\.html$ /showpost.php?p=$1 [NC,L]</pre>
    
    Zend Framework

    If I want to push the envelope further I will need to use Zend Framework to do all this effortlessly. Zend Framework's front controller provides amazing flexibility in terms of how my application URLs can be displayed on the web.

    Zend_Controller_Router_Route, Zend_Controller_Router_Route_Static and Zend_Controller_Router_Rewrite are some of the types of routes available in the front controller. Using a configuration file or issuing relevant directives in the bootstrap file are options that I can use to manipulate my application's URLs.

    By default the front controller uses the controller/action scheme but I can easily change this using a router and adding that router to my controller.

    $router = $frontController->getRouter();
    
    $router->addRoute(
        'post',
        new Zend_Controller_Router_Route(
            'post/:post',
            array('controller' => 'post',
                  'action' => 'show'))
        );
    

    This is a small example on how a simple controller/action sequence can still work as expected and the resulting URL is beautified.

    Final thoughts

    Having easy to remember URLs in an application is a must. It will not only help search engines crawl your site easier - thus making your site more easily discoverable - but it will also help your users remember key areas of your site.

    Zend Framework is by far one of the best solutions available, since it introduces a small learning curve in terms of routing and mod_rewrite while providing pretty URLs. However, for more a complicated rewriting scheme your application might need a very sophisticated .htaccess file.

  • 2009-12-11 12:00:00

    Variables in php.ini

    In my workplace we have been using Zend Framework for more than a year primarily as a glue framework. We have managed to integrate a lot of components from the framework to suit our needs and slowly we are moving towards the full MVC pattern.

    In the meantime our own framework, or collection of code if you prefer, is slowly evolving with every new project. New classes are added while others are enhanced more to provide more flexible input/output. Add to that the continuous evolution of Zend Framework and we are faced with at least one version of our own codebase per project.

    Lately we have been following a more Test Driven Development approach, where we create tests for every component we create or alter. After all this is the purpose of TDDevelopment - to make sure that your code has 100% coverage and that it works!

    The same thing applies when a new version of Zend Framework is released. We download the latest version on the development boxes and run our tests against it. If something has changed and/or is broken we just fix it and our framework is ready for the next project.

    Following this approach, the bulk of our projects are running the latest code (Zend Framework and our own framework). There are however a number of projects that we need to run against an older version of Zend Framework. The reasons for not are not enough money for updating, not enough time, it works so don't tinker with it to name a few.

    So how do we deal with the issue of having different versions of Zend Framework on our servers and including the correct version to the relevant project? The solution that we use is variables in php.ini.

    For starters we have a network share mounted on all of our development servers (the ones that are in house). This share we call it /resources. In there we have all the needed Zend Framework versions i.e.:

    gemini ~ # ls -la /resources/ZendFramework/
    total 0
    drwxrwxr-x 8 webuser webdev 192 Nov  5 05:48 .
    drwxr-xr-x 7 webuser webdev 168 Jul 17 10:55 ..
    drwxrwxr-x 3 webuser webdev  72 Jun 23 13:48 1.0.3
    drwxrwxr-x 5 webuser webdev 216 Apr 21  2009 1.5.2
    drwxrwxr-x 7 webuser webdev 280 Apr 21  2009 1.6.2
    drwxrwxr-x 8 webuser webdev 304 Apr 21  2009 1.7.8
    drwxrwxr-x 8 webuser webdev 296 Jun  8  2009 1.8.3
    drwxrwxr-x 8 webuser webdev 296 Oct 26 12:52 1.9.5
    

    Since this is a network share, all we do is update one location and all servers have access to the same pool of files.

    We also modify the php.ini file of each server, adding the following directives at the end of the file:

    [ZendFramework]
    ZF_LATEST="/resources/ZendFramework/1.9.5/library"
    ZF_1_9_5="/resources/ZendFramework/1.9.5/library"
    ZF_1_8_3="/resources/ZendFramework/1.8.3/library"
    ZF_1_7_8="/resources/ZendFramework/1.7.8/library"
    ZF_1_6_2="/resources/ZendFramework/1.6.2/library"
    ZF_1_5_2="/resources/ZendFramework/1.5.2/library"
    ZF_1_0_3="/resources/ZendFramework/1.0.3/library"
    

    Restarting apache gives us access to those variables using the get_cfg_var PHP function. So in our bootstrap file (called init.php) we have the following:

    $zfPath = get_cfg_var('ZF_1_9_5');
    
    $root = dirname(__FILE__);
    
    set_include_path(
        $zfPath           . PATH_SEPARATOR .
        $root    . '/lib' . PATH_SEPARATOR .
        $root             . PATH_SEPARATOR .
        get_include_path()
    );
    

    Changing to a different version of the Zend Framework can be as easy as changing the path of the ZF_* directive in the php.ini file (and restarting Apache) or by changing the variable we need to use in the init.php file of each project.

    This approach allows us to keep our include_path free from any Zend Framework paths since the server has projects that use different versions of the Zend Framework as well as ours. It also helps us in testing, since we can easily check whether a particular project works as expected in a newer or older version of each framework.

    We opted out from using constants inside .htaccess files, due to the fact that we have many projects and this would have meant that we had to change every .htaccess file, should we wanted to change the version of Zend Framework used.

    php.ini has a lot of directives that can prove useful for the PHP developer. Extending those directives to each project or collection of projects can save you time and headaches.