The Advancing PHP Developer Part 5: Design Patterns

5. Design Patterns

A design pattern is a general reusable solution to a recurring design problem in object-oriented systems. Design patterns are essentially blueprints that suggest how to solve a particular set of OO design problems while adhering to OO best good-practices (which I’ve recounted in my Object Oriented part of this series).

To explain by example, lets have a look at the Model-View-Controller pattern, a common pattern in use on the web and a source of much confusion amongst aspiring developers. The Model-View-Controller pattern (abbr. MVC) is a general solution for decoupling domain logic from the user interface, resulting in much better maintainability for both.

MVC suggests an application structure composed of three basic elements:

  1. Models – which encapsulate domain logic (such as business rules and database access)
  2. Views – which encapsulate presentation logic (such as HTML markup and recurring formatting decorators)
  3. Controllers – which handle the application flow by handling requests and match models to views accordingly.

By separating those three concerns MVC aims to provide a reusable solution for improving maintainability, as each can theoretically be changed independently (in practice, things are never so simple). My personal experience has been that MVC is a huge improvement over common PHP development which promotes spaghetti code since PHP can be very easily integrated with markup (HTML).

The MVC patterns is often used with the Front-Controller pattern, which defines a single entry point to an application and allows for ever greater control of application flow (a technique also known as bootstrapping).

There are plenty of other useful patterns for the web-environment, such as Composite, Singleton (and Registry), Factory and Decorator among others.

Design patterns broke into the software mainstream with the release of the apt named book Design Patterns: Elements of Reusable Object-Oriented Software (which I think any serious developer should read). The WikiWikiWeb, which has the book authors among others as contributors, contains many articles on design patters – such as an overview of its history and a discussion on whether design patterns should be language features to name a few.

Design patterns are not limited to software design, and there are many patterns for design problems in all aspects of web development – such as graphical design and user interactions.

Extra reference material:
Patterns for PHP
User interface patterns for the web
Design patterns in web programming
Web patterns by Berkeley University
Ajax patterns

Previously: Testing, Next up: API

To know when the next article is published, please subscribe to new articles using your Email below or follow me on Twitter.

Subscribe to Blog via Email

Enter your email address to receive notification about new posts.