PHP Design Patterns

Tutorials and Examples of Design Patterns in PHP


Decorator Pattern Added

What if you need to alter the functionality of a class method in some places without altering the original class? The Decorator pattern may be just what you’re looking for, and it comes with a bonus: you can chain object decorators together to add as many features as you need.

As with other design patterns, the Decorator pattern helps with maintainability. It allows you to write reusable code that can affect many objects whenever it is needed, but that will stay out of the way when it is not.


Factory Pattern Added

The Factory pattern helps you create one of a number of interchangeable patterns in a way that is easy to maintain and extend.

One ideal use of the factory pattern is in the concept of drivers. Take, for instance, an application that has the capability to connect to several different types of database engines (MySQL, PostgreSQL, Oracle, etc.). If you encapsulate each driver into its own interchangeable class, your factory can produce one database driver instance on the fly, and the rest of your code can use that database class, not caring which database it is connected to or what the differences are between the database engines.

The Factory pattern is used extensively in PHP frameworks and other applications that aim to be easily configurable and extensible.


Singleton Pattern Added

Today’s design pattern is the Singleton pattern, which makes it impossible to have more than one instance of a class.

Perhaps you have multiple places in your codebase that attempt to open a connection to the database. Without some controls, your code could open multiple connections to the same database.

But with the Singleton pattern, if a connection is already open in an instance of the class, when you try to get an instance of the class, that same instance will always be used.



Welcome to PHP Design Patterns. This site aims to provide information and tutorials for PHP developers looking to incorporate design patterns into their code.

For more information, see our page What’s a Design Pattern?