If you have done any kind of PHP interviews recently, you’ll have heard questions like “What is a design pattern?”. Maybe you know already - maybe you don’t. I’m writing this to help provide a concise, pragmatic list to all the common ones in PHP.
Before doing this, however, it is useful to define what a design pattern is. A design pattern is a code pattern that aims to solve a common, recurring, general problem often using methods and approaches native to object-oriented programming.
If you are not familiar or rusty with PHP OOP fine details, I’d strongly recommend you bring the PHP doc up as you read this.
What patterns do:
- They allow you to dramatically streamline your code and increase your productivity by reducing copy-pasta
- They allow you to build cool techniques to overcome classical modular pitfalls
- They can also, however, if used improperly, cause a lot of headaches, create a lot of hidden bugs, and generally become a living nightmare
Patterns’ best friends:
- Unit testing. By using patterns, you’ll be naturally breaking your code down into stand-alone elements. Unit-testing is the single best way to check that your code still works.
- Frameworks. A lot of frameworks around implement tools to get around the issues brought up by a couple of patterns.
[size=14pt]1. Types of patterns[/size]
Patterns can be creational, structural or behavioral:
- Creational patterns deal with the creation and safe-keeping of an object. Common examples: Factory, Singleton, Prototype.
- Structural patterns consider an object as part of a larger structure, and allows you to generate and implement interfaces for this object. Common examples: Flyweight, Adaptor, Facade
- Behavioral patterns are solely concerned with how an object communicates with other objects, or integrates within a code-base while allowing other objects to query its state. Common examples: Observer, Pub/Sub (known as Mediator), Strategy, Iterator (this one is native within PHP), Promise (this one is not useful in PHP, but is very handy in other languages)
All the common examples noted here will be explored in this tutorial. Please note that [i]whilst this tutorial is aimed at PHP[i], ALL the patterns are universal. They can be implemented in any language that has the notion of classes.
I will structure this into multiple posts, one for each type, and will cross-link them as I type them.