Programming Design Patterns in PHP

Factory Pattern

Falua Temitope O
Devcrib
5 min readDec 13, 2017

--

The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. According to wikipedia, the factory pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.There are several implementations and variants of the design pattern among which we have:

  1. Simple Factory
  2. Abstract Factory
  3. Factory Method

In this article we are going to focus on the Factory method, which has more practical applications, as a side note; the Simple Factory is normally not considered an actual pattern by many developers.

The Factory Method design pattern is one of the twenty-three well-known design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse. The Factory method lets a class defer instantiation it uses to subclasses. It is an interface for creating an object, but let subclasses decide which class to instantiate.

The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects. In Factory pattern, an object is created without exposing the creation logic to the client and refer to newly created object using a common interface.

/* Factory and car interfaces */

interface CarFactory
{
public function makeCar();
}

interface Car
{
public function getType();
}

/* Concrete implementations of the factory and car */

class SedanFactory implements CarFactory
{
public function makeCar()
{
return new Sedan();
}
}

class Sedan implements Car
{
public function getType()
{
return 'Sedan';
}
}

/* Client */

$factory = new SedanFactory();
$car = $factory->makeCar();
print $car->getType(); // which gives a result of "Sedan";

Some of the advantage of factory design pattern are:

  1. Hides product classes from the client/controller, which helps to remove dependencies.
  2. All product classes are made to be polymorphic, thus interchangeable.
  3. It promotes consistency among products, all products should be grouped by the product factories

Bridge Pattern

Bridge pattern is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.

Benefits in using Bridge Pattern

  • Decoupling abstraction from implementation — Inheritance tightly couples an abstraction with an implementation at compile time. Bridge pattern can be used to avoid the binding between abstraction and implementation and to select the implementation at run time.
  • Reduction in the number of sub classes — Sometimes, using pure inheritance will increase the number of sub classes. Let us assume that the full-blown version of our Image Viewer supports 6 image formats in 3 different operating systems. Pure inheritance would have resulted in 18 sub classes whereas applying Bridge Pattern reduces the sub class requirement only to 9.
  • Interface and implementation can be varied independently — Maintaining two different class hierarchies for interface and implementation entitles to vary one independent of the other.

Strategy Pattern

Also known as the power of interface. Strategy pattern is one of the design pattern in which is more suitable to use programmatically when solving a basis daily life problem. Why the consideration in using this pattern?

We do that when we need to choose between similar classes but the only thing that differs is their implementation. In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object. Therefore, context:

  • contains a reference to a strategy object.
  • may define an interface that lets strategy accessing its data.
//generating cupouns for different cars
function generateCupoun($car) {
if($car == "bmw") {
$cupoun = "5% discount";
}
else if($car = "Buggati") {
$cupoun = "3% discount";
}
return $cupoun;
}

Now, let us interface the class car and it will contain the abstract functions of the different type of car.

interface carCupounGenerator {
function isActiveSeason();
function isHighStock();
}

The classes that implement the interface

class bmwCupoun implements carCupounGenerator
{
private $discount = 0;
private $isActive = false;
private $isStockHigh = true;

/**
* @return int
*/
function isActiveSeason()
{
if (!$this->isActive) return $this->discount += 5;
return $this->discount = 0;
}

function isHighStock()
{
if (!$this->isStockHigh) return $this->discount += 9;
return $this->discount = 0;
}
}

$bwn = new bmwCupoun();
var_dump($bwn->isHighStock()); //0

The Context objects contains a reference to the ConcreteStrategy that should be used. When an operation is required then the algorithm is run from the strategy object. The Context is not aware of the strategy implementation. If necessary, addition objects can be defined to pass data from context object to strategy.

Facade Pattern

The purpose of a facade in development and the real world, is to mask something ugly with something attractive. Taking this information, the facade pattern, is a means of converting the ugly interface of one or more classes into a pretty interface, that you will love to work with (hopefully). This is frequently described as creating a unified interface to a sub system or multiple sub systems. Facade and bridge are similar pattern which are used to simplified the usage of a class.

According to jackow, facade can be used with the following methods

  1. Create a wrapper class, this is the facade.
  2. Pass the original ugly class instances to the facade.
  3. Use the facade to abstract away the entire sub system and produce a new beautiful API.

There is a rule guiding the use of pattern which;

the sub system (this is the ugly object) should not be stored as a static attribute inside the facade. This would result in antichrist global state issues.This is due to how PHP shares static attributes between objects.

References

https://www.jakowicz.com/facade-pattern-in-php/

http://phpenthusiast.com/blog/strategy-pattern-the-power-of-interface

www.codeproject.com/Articles/890/Bridge-Pattern-Bridging-the-gap-between-Interface

--

--