Command Design Pattern In PHP

Command Design Pattern In PHP

One of the behavioral design patterns is the Command pattern, this pattern used to map class operations to commands (classes), so let’s see below the components of this pattern.



The command design pattern is a very common pattern in computer science, there are many examples that make use of the command pattern, for example you can think of keyboard clicks as commands, console commands, etc.

In the context of OOP the command pattern enable us to map certain class operations to commands. This enable us to decouble the invoker object from the object that implements the actual operation. Let’s imagine that you have a class calculator, this class contains common calculator operation like (Addition, Subtraction, Multiplication, Division). Now to utilize the command pattern we have to make a class (command) for each operation so we will have AddCommand, SubtractCommand, and so on.


Command Pattern Key Components

  • Receiver Class: This class contains the actual operations and their implementations.
  • Command Interface: This interface needs to be implemented by every concrete command class, and contains just one method execute which calls the receiver class operation.
  • Concrete Commands: Those classes implement the command interface execute method, for example the AddCommand in the calculator.
  • Command Invoker: This is an utility class to set commands and execute them.


Calculator Example

Let’s see the command pattern in action using calculator class. I have prepared a simple calculator class as shown below:


For demonstration purposes this is the calculator class with the four simple operations (Add, Subtract, Multiply, Divide). The next step is to map those operations into commands, but first we need a command interface.



At this point to make a command class we need to implement this interface, let’s see this with the AddCommand



As you see the execute() method class the receiver class add() method for this purpose we injected the receiver class into the constructor.



The command invoker is like entry point to the every command class, we just set commands using the setCommand() method and execute them with the execute() method.

Let’s test this from the command line but first let’s create a client.php file



From the command line you can run

The client.php expects that you pass parameters from the command line, as those parameters will be available through php $argv variable. The above example will output 12

Let’s make other commands for subtract, multiply, divide





Here i updated the client.php to include the operator which identifies the kind of operation and i sent this parameter in $argv[3]. For example to add two numbers:

Other operations can be run also:




Share this: