A Beginner’s Guide to Design Patterns

A Beginner’s Guide to Design Patterns

Ever wondered what design patterns are? In this article, I’ll explain why design patterns are important, and will provide some examples, in PHP, of when and why they should be used.


What are Design Patterns?

Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it’s much more than that. It is a template that has to be implemented in the correct situation. It’s not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.

There are three basic kinds of design patterns:

  • structural
  • creational
  • behavioral

Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

Why should we use them?

Design patterns are, by principle, well-thought out solutions to programming problems. Many programmers have encountered these problems before, and have used these ‘solutions’ to remedy them. If you encounter these problems, why recreate a solution when you can use an already proven answer?

Example

Let’s imagine that you’ve been given the responsibility of creating a way to merge two classes which do two different things based on the situation. These two classes are heavily used by the existing system in different places, making it difficult to remove these two classes and change the existing code. To add to this, changing the existing code requires that you’ll also need to test any changed code, since these sorts of edits, in a system which relies on different components, almost always introduce new bugs. Instead of doing this, you can implement a variation of the strategy pattern and adapter pattern, which can easily handle these types of scenarios.

<?php
class StrategyAndAdapterExampleClass {
	private $_class_one;
	private $_class_two;
	private $_context;
	
	public function __construct( $context ) {
			$this->_context = $context;
	}
	
	public function operation1() {
		if( $this->_context == "context_for_class_one" ) {
			$this->_class_one->operation1_in_class_one_context();
		} else ( $this->_context == "context_for_class_two" ) {
			$this->_class_two->operation1_in_class_two_context();
		}
	}
}

Pretty simple, right? Now, let’s take a closer look at the strategy pattern.


Strategy Pattern

The strategy pattern is a behavioral design pattern that allows you to decide which course of action a program should take, based on a specific context during runtime. You encapsulate two different algorithms inside two classes, and decide at runtime which strategy you want to go with.

In our example above, the strategy is based on whatever the $context variable was at the time the class was instantiated. If you give it the context for class_one, it will use class_one, and vice versa.

Cute, but where can I use this?

Imagine that you’re currently developing a class which can either update or create a new user record. It still needs the same inputs (name, address, mobile number, etc.), but, depending on a given situation, it has to use different functions when updating and creating. Now, you could probably just use an if-else to accomplish this, however, what if you need to use this class in a different place? In that case, you’ll have to rewrite the same if-else statement all over again. Wouldn’t it be easier to just specify your context?

<?php
class User {
	
	public function CreateOrUpdate($name, $address, $mobile, $userid = null)
	{
		if( is_null($userid) ) {
			// it means the user doesn't exist yet, create a new record
		} else {
			// it means the user already exists, just update based on the given userid
		}
	}
}

Now, the “usual” strategy pattern involves encapsulating your algorithms inside another class, but in this case, another class would be wasteful. Remember that you don’t have to follow the template exactly. Variations work as long as the concept remains the same, and it solves the problem.


Adapter Pattern

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

This also lets you alter some of the inputs being received from the client class, making it into something compatible with the adaptee’s functions.

How can I use this?

Another term to reference an adapter class is a wrapper, which basically lets you “wrap” actions into a class and reuse these actions in the correct situations. A classic example might be when you’re creating a domain class for table classes. Instead of calling the different table classes and calling up their functions one by one, you could encapsulate all of these methods into one method using an adapter class. This would not only allow you to reuse whatever action you want, it also keeps you from having to rewrite the code if you need to use the same action in a different place.

Compare these two implementations.

Non-Adapter Approach

<?php
$user = new User();
$user->CreateOrUpdate( //inputs );

$profile = new Profile();
$profile->CreateOrUpdate( //inputs );

If we needed to do this again in a different place, or even reuse this code in a different project, we would have to type everything all over again.

Better

That’s opposed to doing something like this:

<?php
$account_domain = new Account();
$account_domain->NewAccount( //inputs );

In this situation, we have a wrapper class, which would be our Account domain class:

<?php
class Account()
{
	public function NewAccount( //inputs )
	{
		$user = new User();
		$user->CreateOrUpdate( //subset of inputs );
		
		$profile = new Profile();
		$profile->CreateOrUpdate( //subset of inputs );
	}
}

This way, you can use your Account domain again whenever you need it—plus, you’d be able to wrap other classes under your domain class as well.


Factory Method Pattern

The factory method pattern is a creational design pattern which does exactly as it sounds: it’s a class that acts as a factory of object instances.

The main goal of this pattern is to encapsulate the creational procedure that may span different classes into one single function. By providing the correct context to the factory method, it will be able to return the correct object.

When can I use this?

The best time to use the factory method pattern is when you have multiple different variations of a single entity. Let’s say you have a button class; this class has different variations, such as ImageButton, InputButton and FlashButton. Depending on the place, you may need to create different buttons—this is where you can use a factory to create the buttons for you!

Let’s begin by creating our three classes:

<?php
abstract class Button {
	protected $_html;
	
	public function getHtml()
	{
		return $this->_html;
	}
}

class ImageButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your image-based button
}

class InputButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your normal button (<input type="button"... />);
}

class FlashButton extends Button {
	protected $_html = "..."; //This should be whatever HTML you want for your flash-based button
}

Now, we can create our factory class:

<?php
class ButtonFactory
{
    public static function createButton($type)
    {
        $baseClass = 'Button';
        $targetClass = ucfirst($type).$baseClass;
 
        if (class_exists($targetClass) && is_subclass_of($targetClass, $baseClass)) {
            return new $targetClass;
		} else {
            throw new Exception("The button type '$type' is not recognized.");
		}
    }
}

We can use this code like so:

$buttons = array('image','input','flash');
foreach($buttons as $b) {
    echo ButtonFactory::createButton($b)->getHtml()
}

The output should be the HTML of all your button types. This way, you would be able to specify which button to create depending on the situation and reuse the condition as well.


Decorator Pattern

The decorator pattern is a structural design pattern which enables us to add new or additional behavior to an object during runtime, depending on the situation.

The goal is to make it so that the extended functions can be applied to one specific instance, and, at the same time, still be able to create an original instance that doesn’t have the new functions. It also allows for combining multiple decorators for one instance, so that you’re not stuck with one decorator for each instance. This pattern is an alternative to subclassing, which refers to creating a class that inherits functionality from a parent class. As opposed to subclassing, which adds the behavior at compile time, “decorating” allows you to add new behavior during runtime, if the situation calls for it.

To implement the decorator pattern, we can follow these steps:

  1. Subclass the original “Component” class into a “Decorator” class
  2. In the Decorator class, add a Component pointer as a field
  3. Pass a Component to the Decorator constructor to initialize the Component pointer
  4. In the Decorator class, redirect all “Component” methods to the “Component” pointer, and
  5. In the Decorator class, override any Component method(s) whose behavior needs to be modified

Steps courtesy of http://en.wikipedia.org/wiki/Decorator_pattern

When can I use this?

The best place to use the decorator pattern is when you have an entity which needs to have new behavior only if the situation requires it. Let’s say you have an HTML link element, a logout link, that you want to do slightly different things to based on the current page. For that, we can use the decorator pattern.

First, let’s establish the different “decorations” we’ll need.

  • If we’re on the home page and logged in, have this link be wrapped in h2 tags
  • If we’re on a different page and logged in, have this link be wrapped in underline tags
  • If we’re logged in, have this link wrapped in strong tags

Once we’ve established our decorations, we can start programming them.

<?php
class HtmlLinks {
	//some methods which is available to all html links
}

class LogoutLink extends HtmlLinks {
	protected $_html;
	
	public function __construct() {
		$this->_html = "<a href=\"logout.php\">Logout</a>";
	}
	
	public function setHtml($html)
	{
		$this->_html = $html;
	}
	
	public function render()
	{
		echo $this->_html;
	}
}

class LogoutLinkH2Decorator extends HtmlLinks {
	protected $_logout_link;
	
	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<h2>" . $this->_html . "</h2>");
	}
	
	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

class LogoutLinkUnderlineDecorator extends HtmlLinks {
	protected $_logout_link;
	
	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<u>" . $this->_html . "</u>");
	}
	
	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

class LogoutLinkStrongDecorator extends HtmlLinks {
	protected $_logout_link;
	
	public function __construct( $logout_link )
	{
		$this->_logout_link = $logout_link;
		$this->setHtml("<strong>" . $this->_html . "</strong>");
	}
	
	public function __call( $name, $args )
	{
		$this->_logout_link->$name($args[0]);
	}
}

We should then be able to use it like so:

$logout_link = new LogoutLink();

if( $is_logged_in ) {
	$logout_link = new LogoutLinkStrongDecorator($logout_link);
}

if( $in_home_page ) {
	$logout_link = new LogoutLinkH2Decorator($logout_link);
} else {
	$logout_link = new LogoutLinkUnderlineDecorator($logout_link);
}
$logout_link->render();

We can see here how we are able to combine multiple decorators if we need them. Since all the decorators use the __call magic function, we can still call the original function’s methods. If we assume that we are currently inside the home page and logged in, the HTML output should be:

<strong><h2><a href="logout.php">Logout</a></h2></strong>

Singleton Pattern

The singleton design pattern is a creational design pattern which makes sure that you have one single instance of a particular class in the duration of your runtime, and provides a global point of access to the single instance.

This makes it easier to set up a point of “coordination” for other objects that use the singleton instance as well, since the singleton’s variables will always be the same for anything that calls it.

When can I use this?

If you need to pass a specific instance from one class to another, you can use the singleton pattern to avoid having to pass the instance via constructor or argument. Imagine that you have created a Session class, which simulates the $_SESSION global array. Since this class will only need to be instantiated once, we can implement a singleton pattern like so:

<?php
class Session
{
	private static $instance;
	
	public static function getInstance()
	{
		if( is_null(self::$instance) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	private function __construct() { }
	
	private function __clone() { }
	
	//  any other session methods we might use
	...
	...
	...
}

// get a session instance
$session = Session::getInstance();

By doing this, we can access our session instance from different parts of our code, even in different classes. This data will persist throughout all getInstance calls.


Conclusion

There are many more design patterns to study; in this article, I’ve only highlighted some of the more prominent ones that I use when programming. If you’re interested in reading about the other design patterns, Wikipedia’s Design Patterns page has a plethora of information. If that’s not enough, you can always check out Design Patterns: Elements of Reusable Object-Oriented Software, which is considered to be one of the best design pattern books available.

One last thing: when you use these design patterns, always make sure that you’re trying to solve the correct problem. As I mentioned previously, these design patterns are a double-edge sword: if used in the wrong context, they can potentially makes things worse; but if used correctly, they become indispensable.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.jordanwalker.net Jordan Walker

    Great guide for beginners on PHP patterns!

  • http://www.juancarlosrois.com Juan C. Rois

    Excellent article, Thanks a lot Nikko.

    I’m a self-taught developer and PHP has been somewhat tricky to learn for me, I still have a lot to learn but articles like this help me a lot with the theory that I have not been able to learn by my self.

    There are countless tutorials and websites from which one can learn a lot, but not many of them explain the theory and logic behind our apps and scripts.
    Thank you.

  • http://hetal.wordpress.com Hetal Bhagat

    Exactly what I was waiting for… Excellent article.

  • Zoran

    Hey, thanks for this, design patterns can be useful when doing OOP PHP, though some may lead into problems if not integrated properly.
    Magento has one of the best implementation of design patterns in their code btw!

  • http://freecss.info CSS Tutorials

    Thanks, I had never even heard of design patterns until this tutorial.

  • amidude

    Thank you so much for this in-depth tutorial.

  • http://twitter.com/xrommelx xrommelx

    thank for this NetTuts+

  • http://http//www.intutorials.com Chris

    Wow, nice read – this takes me back to my university days….

  • emehrkay

    Great write up with solid examples. I love the use of underscore prefixing private members.

    If you want to further understand patterns I’d recommend Patterns of Enterprise Application Architecture by Fowler

  • Brook

    While this article seems focused on PHP most of these patterns apply to C#/ASP.Net also, valuable knowledge regardless of which toolbox you may be using during the day. Keep the knowledge flowing!

    • http://nikkobautista.com Nikko Bautista
      Author

      I agree – design patterns should be applicable regardless of the language you use. :)

  • http://www.jeffadams.co.uk Jeff Adams

    i have no idea what that all meant but thanks all the same!

  • Patrick

    And noone tells, that some of this design patterns are really useless. Especially the “decorator” pattern.

    Never think too complicated and you’ll save runtime. That’s because most of all CMS, Blogs etc are too slow.

    • RCKY

      Important article for every one that claims himself to be a programmer. Patterns are intendet to solve common problems and keep software maintainable and scalable.
      1. Since php is is quite slow it doesn’t make sense to implement a complex pattern in a small system, thats right, but according to “bigger” web applications it will bring you a lot of benefit.
      2. To know (e.g. the GOF) patterns can make you definitely a better programmer! At least the patterns mentioned above aren’t language specific and there are are a lot of languages where e.g. the object instantiation is much cheaper …

  • http://www.lajmar.com John Ramirez

    Nice bro this is a great post for object oriented php well detailed for beginners.

  • salman

    excellent, nice simple examples, need more on this, bit more in depth

  • http://www.jsxtech.com Jaspal Singh

    Excellent tutorial to Design Patterns for beginners.
    Thanks for sharing.

  • umut

    Thanks great work

  • http://twitter.com/m_chaurasia Mukesh

    it is so helpful for me & i think many of people who related to development.
    Thanks for sharing

  • http://www.digichroma.com aryan

    WOW! Please make it a series, and publish advance tutorials too. Would love to see video tuts series on it.

    Thanks!

    • http://mitchmckenna.com Mitchell McKenna

      Agreed, I’d love to see this turned into an in-depth series with more examples on even more design patterns.

  • http://www.dangermoose.co.uk flashmac

    Cheers bud, this will come in handy today when I start to build my FormBuilder class.

    Good article to kick start the day.

  • Dalibor Sojic

    Great tutorial.

  • Sajan

    Great article.. Thanks for publishing.

  • zylo

    Yawn!!! are we done yet! :P come on guys! this post was too long… tuts have become borin lately!!!

  • http://www.satya-weblog.com Satya Prakash

    The articles looks cool. Planned for today’s evening read.

  • Xander

    People, if you like this please buy books like O’reilly Design Patterns.
    It’s the best reference for Actionscript coders, but the design patterns can be used for PHP also.
    All the design patterns are described in full detail.

    • chris

      +1 vote for O’Reilly’s Design Patterns book.

  • http://kevinrodrigues.com/blog Kevin Rodrigues

    Frankly, I don’t know much about design patterns and did not understand a lot of the stuff mentioned here. And could not relate as to how they make things easier (description and examples look complicated for a beginner). Perhaps I need to learn more about design patterns and their application.

    But thanks for putting up lots of information about design patterns.

    • http://nikkobautista.com Nikko Bautista
      Author

      I know what you mean – when I first learned of Design Patterns in my college days, I never really appreciated how useful they would be. It was only when I found myself in the situation to use these design patterns that I fully understood how they work. Hopefully, you’ll find yourself in the same situation, I guarantee you’ll be able to appreciate them as well.

      Thanks for reading the article!

    • Rob

      Totally agree. It’s like giving a name to your thought patterns. So what? I’m not going to look up a thought in a book or article before I pursue it. It all seems pure nonsense to me and serves only to box a person in to those patterns and may block creative thinking. What hogwash!

  • http://www.publicstatic.net Mike

    Haha, great image of Singleton. The design pattern is the first thing I think of every time I see that awesome scotch.

    • http://nikkobautista.com Nikko Bautista
      Author

      Haha! I had a hard time looking for a good image to represent the Singleton pattern – the scotch was the best Google could offer me, so that’s the one I went for.

  • Tim

    have been looking for something like this, great work and thats alot for sharing…
    very much appreciated!!!!

  • Eric de Oliveira Campos

    Excellent, I’m using it with Microsft’s C# ASP.NET 3.5, thanks for the guide!

  • http://www.shiftedwork.de Daniel S

    Great Tutorial – but what is with the REGISTRY PATTERN? This is an important Pattern to handle config files etc…

    And – PLEASE – please publish “namespaces for beginners” :)

    Greetings from Germany,

    Daniel

  • CW

    Nice article, I just hope people are reading it right and paying attention to the where can I use this. Common mistake for people new to patterns is to try to use a pattern regardless of it is fits their problem. Though that said I don’t think you stress the more important point of the singleton enough “ENSURE A CLASS ONLY HAS ONE INSTANCE” and not only ensure it but only use it when there should be only one in any application that would ever use that class.

    • http://nikkobautista.com Nikko Bautista
      Author

      I understand what you mean – some programmers try to use the Singleton pattern to “make up” for features that they miss from procedural programming. I did try to reiterate though that design patterns are a double-edged sword, can be both useful and deadly at the same time. Hopefully that statement is taken seriously.

      Thanks for the compliment!

  • as9

    Yeah good for newbies.
    But this is not the complete design patterns technique.

    I hope the next tutorial are complete.

    Thanks

    • http://nikkobautista.com Nikko Bautista
      Author

      I don’t think it’s feasible to put in all the design patterns in one tutorial, so I opted to put in only those I find most useful to me, and those that would probably be most useful to beginners, hence the title, “A Beginner’s Guide to Design Patterns” :)

  • yoh

    nice article. i use strategy combined with adapted pattern. it is very practical :P

  • The Fisher

    “The strategy pattern is a behavioral design pattern that allows you to decide which course of action a program should take, based on a specific context during runtime”

    “The weather pattern is a behavioral design pattern that allows you to decide to go to the beach on sunny days or to stand beside your fireplace in cold winter nights. One more level of complexity may be introduced considering that a sunny day may easily be a damn working monday or that in cold winter night you might have something better to do than faking fairy tales grandmas. Don’t understimate this pattern, it may change your life”

    And so on.

    I will enjoy any other attempt to pack a sheer banality with a flamboyant set of tech-like words.

    (It’s not for you, Nikko, it’s right for design patterns)

  • http://nikkobautista.com Nikko Bautista
    Author

    Thanks for the compliments guys! Hope you’ll enjoy my other future articles :)

  • PauloN

    +1 design pattern, this blog is a nice start for those who want to learn deep into classes and its structure.

  • amit

    Though we would all like to be able to do website designing for own website, we all aren’t able to, whether we just don’t understand the various elements or we just don’t have the time or don’t have the required expertise; the use of a top website design company is a must have. Just any website design company will not do; there are various things that can make a web design company a best web design company who will provide the exact services you need to meet the exact specifications you provide and request.

  • a77icu5

    ….I have a couple of questions:

    1.- What will happen with registry pattern in php6?…return by reference = error.

    2.- how I can represent the registry pattern in UML? the reason is that UML says that relations ‘many->one’ should be avoided but registry pattern improvement the performance.

  • http://www.thomascraigconsulting.com Thomas Craig Consulting

    Nikko, great article with excellent explanations.

  • http://wildanr05.student.ipb.ac.id wildanr

    Nice tutorial, maybe you guys should follow up this article with real world example of design pattern usage in the real world.

  • http://kosharirecipe.blogspot.com/ Koshari

    Very helpful guide. And nice samples. thanks for sharing

  • http://okalex.tumblr.com Alex Parkinson

    Nice post. I’d love to see more like this. I wrote a brief post detailing an extendable Singleton class in PHP here: http://okalex.tumblr.com/post/766928795/extending-singleton .

  • http://www.colondraino.com Colon Cleansing

    I remember 10 years ago starting out as a C++ programmer never having heard of the concept of design patterns. I remember having a hard time writing code as I was convinced there were patters to solutions I could come up with. I was quite happy to learn the GOF came up with more than I needed and that there actually was such a thing as design patterns.

  • AM

    Nikko, I kept reading your article and felt like I had seen it somewhere before. So I looked into my bookmarks and found the original. Your material was taken from this page: http://www.dofactory.com/Patterns/PatternFactory.aspx. I wasn’t impressed.

    • http://nikkobautista.com Nikko Bautista
      Author

      Er, sorry but I didn’t take any material from that site.

    • http://www.judeosborn.com Jude Osborn

      AM, there’s tons and tons of similar info on line about design patterns. Nikko is simply providing a basic introduction to them, not claiming he made them up.

  • Okeowo Aderemi

    Design Patterns are very tricky but once you get the hang it will be like another language my favourite is the Singleton Pattern suitable for web applications that deal with large Database calls i usually load the db in a session and any other call will lead you straight to the same object though still confused if loading all info to sessions are safe

  • http://www.fajascorset1.co.cc shapewear

    Frankly, I don’t know much about design patterns and did not understand a lot of the stuff mentioned here. And could not relate as to how they make things easier (description and examples look complicated for a beginner). Perhaps I need to learn more about design patterns and their application

  • http://www.realtimemanager.net/ Rick

    The concept is good, but maybe should have been shown in pseudo code for people that don’t know PHP.

  • http://zumba25.multiply.com/journal dance zumba

    Excellent post! I’m only starting out in community management/marketing media and learning how to make it work well – resources such as this post are incredibly helpful. As our organization is dependent in the US, it?s all a little bit new to us. The example above is something that I be concerned about as nicely, how to show your special genuine enthusiasm and write concerning the fact that your product is useful in that circumstance.

  • http://2rangi.com Hossein

    Very useful ! Nice samples and good describing .
    Thanks alot !!!

  • http://www.reklam-fabrikasi.com webtasarimizmir

    Design patterns can’t be introduced better. Without getting into too much detail and clarifying with code fragments made this post an excellent resource. Great work.

  • Crashdaddy

    I was halfway into the adapter pattern before I realized it was a beginner’s guide! Excellent guide. You are very right. This is just how I do it.