The 5 Most Common Design Patterns in PHP

Design patterns  in PHP provides the idea to follow common patterns that makes developer easier to manage code and its easy to understand and speed up development process.

 

Design patterns are defined into three category  –

1. Creational Patterns  – This patterns are used in object creation technique for creating the objects that decoupled from implementing system.

2. Structural Patterns  – It is identifying the way to realize the relationship between entities.

3. Behavioual Patterns –  This design patterns are used to manage relationship, algorithm and responsibility objects.

 

 

design patterns in php
design patterns in php

 

Lets look at some common used design patterns in PHP –

 

Factory  –

It is creational design pattern that create the object when we want to build and assigned it .It solves the problem for creation object of class and we define into dedicated class that having main responsibility for creating objects. It is most commonly used design patterns  in PHP.

 

Lets look at below code , we implement the factory design patterns with interface in php –


interface FriendInterface {
    public function create() : Friend
}

 

Now, We implement friend interface with following classes –

 

class FriendFactory implements FriendInterface 

{    public function create() : Friend 

{
    $friend = new Friend();        
       // initialize your friend        
       return $friend;
    }
}

 

Please have a look at above code , Its awesome patterns and powerful .

There are some below  benefit for factory patterns  :

. If you want to change ,replace and rename the base class later on, there are no need to jump into every pages.

. If we need to create the objects there are no need to create every time, Just  we create the objects into factory class that what we want to used it.

.For creating complex logic, Its might be not better choice

 

Singleton

It is used to create only one instance of class. Suppose if we create the object once of class then we cant create object anymore. __construct is defined private in this class so it prevents for creation the direct objects of class.It is very useful to access the single object throughout projects.

 

Lets look at below code patterns  –

class Singleton
{
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct()
{
}
private function __clone()
{
}
private function __wakeup()
{
}
}
class ChildPattern extends Singleton
{
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());
$obj2pattern = ChildPattern ::getInstance();
var_dump($obj2pattern === Singleton::getInstance());
var_dump($obj2pattern === ChildPattern ::getInstance());

 

 

From above code , Its very clear that when you want to have single object across the system, This design patterns will be very useful. Its very useful for connecting database and create the objects to access global.

 

Lets moving for another design patterns  –

 

Observer Pattern in PHP –

This design pattern is used to notify the rest of system about certain events at particular place.

For Example, we create Theater to show movies for the critics . We just define class name theater with methods .  Before starting movie , we want to send message to citic’s phone, In middle of movie , We want to stop movie for 10 minutes and lets have interval. In  observer patterns , object get alerts when status is changed .

 

Lets look at below code style for observer pattterns  –

 

class Theater {
 
    public function current(Movie $objmovi) : void {
     
        $criticsEvents = $objmovi->getCritics();
        $this->message->send($criticsEvents , '...');

        $objmovi->play();

        $objmovi->pause(10);
        $this->progress->interval($criticsEvents )
        $objmovi->end();

        $this->response->request($criticsEvents );
    }
}

 

Lets move for another design patterns –

 

Decorator Pattern  –

This is used when want to change the behavior of class objects at run time  , removes unnecessary inheritance and number of class.

suppose we take class that is sofa and bed, It implements SleeperInterface.

 

interface SleeprInterface {
public function sleep() : void;
}
class Sofa implements SleeperInterface {
public function sleep() : void {
// sleeping on sofa
}
}
class Bed implements SleeperInterface {
public function sleep() : void {
// sleeping on bed
}
}

 

 

Lets add another features tracking  for sofa and bed , if someone sleep on sofa or bed , just track the time.By using inheritance we can solve this issue .

 

 

class SofaTracking extends Sofa {
public function sleep() : void {
parent::sleep();
$this->sleepHoursTrack();
}
}
class BedTracking extends Window {
public function sleep() : void {
parent::sleep();
$this->sleepHoursTrack();
}
}

 

 

It is very surprising that we have used here four classes to resolve the issue , But we can resolve this issue by three class from using Decorator pattern smartly.

 

class SmartSleeper implements SleeperInterface  {

private $sleeper;
public function __construct(SleeperInterface $sleeper) {
$this->sleeper = $sleeper;
}

public function sleep() : void {
$this->sleeper->sleep();
$this->sleepHours();
}
}
$sofaobj = new Sofa();
$bedobj = new Bed();
$sofawithSmart = new SmartSleeper ($sofaobj);
$bedwithSmart = new SmartSleeper ($bedobj);

 

 

Hopefully , you will get have better idea, How design patterns help in your common patterns and it helps you to manage code in easier way.

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *