An introduction of PHP Design Patterns

Utpal Biswas
Oceanize Lab Geeks
Published in
2 min readSep 17, 2018
Design Patter

What is this ?

Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development.

Design Patterns have two main usages in software development arena.

  1. Common platform
    A singleton design pattern signifies use of single object so all developers familiar with single design pattern will make use of single object and they can tell each other that program is following a singleton pattern.
  2. Best Practices
    Learning these patterns helps inexperienced developers to learn software design in an easy and faster way.

There are so many like 23 design patterns which can be classified in three categories: Creational, Structural and Behavioral patterns. but here i will share the mostly used design pattern “Factory Pattern” in the software development.

Factory Pattern:

One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the object you want to use. Consider the following example is using the factory pattern:

<?phpclass Automobile
{
private $vehicleMake;
private $vehicleModel;
public function __construct($make, $model)
{
$this->vehicleMake = $make;
$this->vehicleModel = $model;
}
public function getMakeAndModel()
{
return $this->vehicleMake . ‘ ‘ . $this->vehicleModel;
}
}
class AutomobileFactory
{
public static function create($make, $model)
{
return new Automobile($make, $model);
}
}
// have the factory create the Automobile object
$veyron = AutomobileFactory::create(‘Toyota’, ‘Honda’);
print_r($veyron->getMakeAndModel()); // outputs “Toyota Honda”?>

This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.

The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.

Here is some references if you want to learn more and dive into it.

Architectural pattern on Wikipedia
Software design pattern on Wikipedia
Collection of PHP design pattern

--

--