Implementation of Command Pattern in PHP

By

Command Pattern encapsulates everything needed to execute an action. In this article, we will be going through the command design pattern in PHP.

Command is a very useful design pattern, whose intent is to encapsulate a request as an object. One of the biggest advantages to this pattern is that it decouples the object that invokes the operation from the one that actually knows how to perform it.

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action – Wikipedia

The definition of Command provided in the original Gang of Four book on DesignPatterns states:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

Show Me The Code!

To demonstrate how the Command Pattern works, let’s have a look at an abstract PHP class which implements the PHP Interface class. Here’s the definition of the AbstractCommand class:

In AbstractCommand class, there is one abstract method processCommand and should be implemented to execute a particular command. Let’s do a real world example using the abstract class.

execute() Method:

Method uses following methods:

  • preExecution
  • processCommand
  • postExecution

execute() method invokes pre and post execution methods, processes command, sets the response and finally returns the object ($this). Class object is returned to leverage method chaining and with the help of method chaining we can call more than one method of the class in single instruction.

SignupCommand and Usage

Summary

In this post we explore the Command pattern with one real world example. Although the example in this post is simple one, the purpose was to communicate the basic concept rather than a full explanation of every single usage scenario.

References

To know more about command pattern and design patterns. Have a look at following resources: