Applying design patterns to web development

2 comments

Part 1: The strategy pattern

One of my biggest efforts as a developer is to apply design patterns to my software designs and implementations. When I’m working with PHP is where I most feel the lack of OO approaches in many cases. PHP started as a procedural language, with a few functions serving for a limited amount of tasks, but like anything in this world, it has evolved into a more mature language. The problem is that many tutorials around the web are meant for starting as a developer and tend to leave Object Orientation out of the box, which is a trend that I find awful.

Sadly, there are still many PHP developers writing procedural code and calling it object oriented because they use the word class. Writing OO code is a bit more complex than that, we need to “think” how to express our problem into objects and how to make them communicate, not to create monolithic systems with strongly coupled components, which turns into software impossible to maintain, document, test and most importantly reuse and scale.

Well, back to the main idea, in this blog post I intend to use the strategy design pattern, which is one of the most implemented design patterns when it comes to web systems. The definition of the strategy pattern is:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

The classic scenario is a situation where we can employ different variants depending on the environment. For instance, Session Management is an important task on every web application. If we are going to create a small application, then using the standard PHP session implementation, we are good to go. But this does pose two main problems:

  1. If we are in a shared hosting, anybody in the same server can work around the server´s security and copy the session files thus gaining access to data we don’t want them to have.
  2. If we want to scale our application, like adding extra servers, moving the application to a cluster or something like it, sharing the session files is a nightmare for managing the sessions

So, we have two main scenarios, where we are able to use the standard session driver and where we have to use a more advanced session management system, like for instance a database approach or integrating with Memcached or another powerful solution.

The initial approach is to write a PHP file called sessions.php and there do something like this:

$driver = $configuration[“session”]->getFile();
include $driver . “.php”;

And driver would be a file performing the calls to the session_set_save_handler function which changes the functions for managing the sessions, and of course, the implementation of such functions.

An approach like that one does the job, but we would have no objects, just a bunch of files. The real Object oriented version would be defining the contract of how we want to interact with the drivers. In our case, we have a session driver, which could hold a few operations, basing on the session_set_save_handler function arguments, we would need 6 methods in our interface: Open, Close, Read, Write, Destroy and GarbageCollect.We would have something like this:

interface ISessionDriver
{
   public function Open();
   public function Close();
   public function Read();
   public function Write();
   public function Destroy();
   public  function GarbageCollect();
}

Now, we have an interface, and we can register the interface as the session provider. To do that we have again two methods, the first one is loading from the configuration the class we want to load, and we’ll see the second soon on how to use Dependency Injection.

The idea is very much like the first functional approach, include the template file, but now we know that we’ll have a class implementing the ISessionDriver interface, a class which respects a contract previously established by me. Again, we would do a code quite similar, but now we would check:

$driver = $configuration[“session”]->getFile();
   include $driver . “.php”;
   $driverInstance = new $driver();

   if ($driverInstance instanceof ISessionDriver){
      //register the session driver
   }
   else
      throw new SystemException(“Expecting an ISessionDriver here!”);

With that we finish the first part of how to decouple our classes into a more reusable environment, applying the strategy design pattern and we will get deeper into it soon by using dependency injection to make this design even more decoupled.

Source code is highlighted!

0 comments
Thanks to Alex Gorbatchev's Syntax Highligther and a really smooth guide found here now the posts have full source code coloring!

I should be migrating older posts soon..

The whole blog is migrated to Gorbatchev's syntax highlither!

Using Propel with CodeIgniter

10 comments

CodeIgniter is a nice development framework used for PHP applications. Is light, small, compact and it does provide an “Object Oriented” solution for web development. However, it lacks a major component, which is a database infrastructure. CodeIgniter’s models provide a rather quick and dirty solution for database access, which is nice for small projects, because we cannot be thinking on the large solution every time we write a piece of code, but for most decent application, a small approach like that one, just won’t do it.


The solution? Well, using an ORM framework. I’m a defender of ORM mapping solutions and I believe that they are here to stay, just like the Korn song. Anyways, there is no easy way to integrate CodeIgniter with Propel; they just don’t seem to get along. I’ve read a wiki post explaining how to do it, but I found it quite disturbing for a few reasons


  • A solution shouldn't tell you to change the apache configuration
  • Propel has a really powerful autoloading system, why did they not prepared for using it?

Anyways, the idea I came up with is to integrate Propel as an independent library for the framework using the libraries autoloader, which is much like the post I'm talking about, but I made a few tweaks. CodeIgniter stores it’s plugins into the folder system/libraries, so the best way to start is copying Propel’s runtime into that folder. Create a folder called propel and copy the runtime files (propel/runtime/lib/*) there.


After copying Propel we can create the library’s entry point, which is a file called propel.php and there we will write a class to load Propel:


class CI_Propel
{
  public function CI_Propel()
  {
 define(DIRECTORY_SEPARATOR, “DS”);
     require dirname(__FILE__) . DS . "propel" . DS . "Propel.php";
     Propel::init(BASEPATH . "application/config/propel-conf.php");
  }
}

In this class we require the Propel main file (Propel.php) and we tell it where he can find the configuration file. The configuration file is the xml file generated by Propel storing the database configuration and we must specify it in order to get propel running.


Now we’ve created our driver, we need to tell CodeIgniter to load our library, and this is done by going into the application/config/autoload.php file, where CI stores the libraries to be loaded with the application. We need to look for the line:


$autoload['libraries'] = array();

And change it with the information we need to load propel:


$autoload['libraries'] = array('Propel');

Now, we need to copy Propel’s models into the models folder located in the application folder and the configuration files generated should be on the application/config folder. Now the mapping configuration files should be edited to load the models properly; Propel works with relative routes to the models and it breaks when we try to load those models from a different path. You should look for lines like this one:


'CategoriesTableMap' => 'Northwind/map/CategoriesTableMap.php'

And change them for the real CI path:


'CategoriesTableMap' => BASEPATH . DIRECTORY_SEPARATOR . "application" . 
DIRECTORY_SEPARATOR . 'models/map/CategoriesTableMap.php'

Well, all we need to do now is use Propel! Keep in mind that using Propel’s classes directly from the controller is a bad practice, because you’d be coupling your data access layer to your presentation layer, you can take a look on this post if you want to read a bit more about it.


For our practical purposes we can just call the Propel query object from the controller now, much like this:


function index()
{
  $query = ProductsQuery::create()->limit(10)->find();
  $data =  array();
  $data['rows'] = $query;

  $this->load->view('welcome_message', $data);
}

And it will retrieve the results quickly and using a nice ORM mapper. I hope you’ve found this post useful and as usual commenting is highly encouraged!

New year!

0 comments
New year starting, and I need to set up a few goals. First, I will be creating my own template, because like Scott Hanselman said, using a provided template in a blog might just look lame.

The second thing I need to do is post more stuff. I've been working on some cool stuff, and I think that I should post them, so people can see it and perhaps I can help someone out there!

That's the things I'm going to be working on this month to boost my blog a bit. Anyone who reads this, just wish u all a happy new year!