PHP Visitor Design Pattern II: The Double Dispatch

visitor2x

The Visitor pattern uses a double dispatch even with languages that are inherently single dispatch (such as PHP). In this second installment of the Visitor, I’d like to look at the concept and utility of double dispatch and role of the ObjectStructure in creating a working Visitor example that can be transformed into a practical application.

In Part I PHP Visitor Design Pattern I: The Single Dispatch, the focus was on using a single dispatch and a “pretend visitor.” This post shows how to create a visitor object based on both a Visitor interface and ConcreteVisitor implementations that are used in concert with the Element participants via the ObjectStructure. In order to do this, a couple more concrete Elements have been added to the example begun in Part I of the Visitor.

The Visitor Design Pattern Diagram

The Part I Visitor post suggests that the Visitor class diagram is a bit daunting, and so I held off until now to show it. If you look at the bottom portion of Figure 1, you will see that the example in Part I handled all of the Element participants, and included a “pretend visitor” where the Accept(Visitor) implementation in an actual Visitor pattern goes. So, you have some idea of what close to half of the Visitor does.

Figure 1: Visitor Class Diagram

Figure 1: Visitor Class Diagram

You can get a hint at what double-dispatch is by looking at the dual connections that the Client has to both the Visitor and Element (via the ObjectStructure). In the pattern, the Client is implied, but it’s clear to see the double reference to both the Visitor and the ObjectStructure which holds a reference to the Element.

This particular implementation of the Visitor pattern extends the example used in Part I where a “pretend” visitor is an operation that provides the fill color of SVG images. In this implementation, the fill color operation is provided by an actual visitor object. A third and forth Element class have been added, one with a visitor (Triangle) and one that does not have a visitor (zigzag lines have no fill colors—just a stroke color.) Figure 2 shows the program as a file diagram:

Figure 2: File diagram of Visitor pattern in PHP

Figure 2: File diagram of Visitor pattern in PHP

To get an idea of what the application does and look at the overall code, run the program and download the files:
PlayDownload

When you run the program, you can see that the shape (concrete Element) and the color (concrete Visitor) are selected separately. Those separate selections are to highlight the concept of double-dispatch. A shape and color are selected with the understanding that the developer had not included a fill color originally, and instead of starting from scratch to re-program the shape selector, the developer added a visitor. To see how double-dispatch works in a Visitor pattern, follow the path from the Client to the ObjectStructure and to the IElement::accept() method.

Double-Dispatch and Traversing Elements with Visitors

Figure 3: ObjectStructure and IElement::accept() double-dispatch link

Figure 3: ObjectStructure and IElement::accept() double-dispatch link

One of the key participants in the Visitor pattern is the ObjectStructure class. The Gang of Four introduce the ObjectStructure participant to handle traversing the Element objects that may need the attention of a Visitor. The pattern solves the double-dispatch problem by including a concrete visitor in the Element::accept(IVisitor) method. However, the path from Client-request to double-dispatch first goes through the ObjectStructure class. By looking the Client, ObjectStructure and a concrete Element, you can see the double-dispatch process:

< ?php
/*
* CLIENT
*/
//Client.php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
//Autoload code
function includeAll($className)
{
    include_once($className . '.php');
}
spl_autoload_register('includeAll');
 
//Begin Client class
class Client
{
    private static $shapeElement;
    private static $color;
    //client request
    public static function request()
    {
      self::$shapeElement=$_POST['shape'];
      self::$color=$_POST['color'];
 
      $obStructure = new ObjectStructure();
      $obStructure->attach(new self::$shapeElement());
      $colorVisitor= new self::$color();
      echo $obStructure->confirm($colorVisitor);
    } 
}
Client::request();
?>
 
 
< ?php
/*
* OBJECT STRUCTURE
*/
//ObjectStructure.php
class ObjectStructure
{
    private $elements=array();
 
    public function attach(IElement $element)
    {
         array_push($this->elements,$element);
    }
 
    public function confirm(IVisitor $visitor)
    {
         foreach($this->elements as $elementNow)
         {
              return $elementNow->accept($visitor);
         }
    }
}
?>
 
 
< ?php
/*
* ELEMENT
*/
//Circle.php
class Circle implements IElement
{
    private $visColor;
 
    public function accept(IVisitor $visitor)
    {
        $visitor->visitCircle($this);
        return $this->showShape();
    }
 
    private function showShape()
    {
        $circleShape= IElement::SVG . "<circle cx='110' cy='110' r='100' fill='{$this->doColor()}' stroke='blue' stroke-width='1' />";
        return $circleShape;
    }
 
    public function setColor($visitorColor)
    {
         $this->visColor = $visitorColor;
    }
 
    private function doColor()
    {
        return $this-> visColor;
    }
}
?>
 
</circle>

Stepping through the process, the Client first (1) instantiates an instance of ObjectStructure. Second (2) the Client uses the ObjectStructure::attach() method to push the selected element instance onto an array. Third (3) the Client passes the selected visitor to the ObjectStructure::confirm() method, which in turn, fourth (4) calls the Element::accept($v) method which passes the concrete visitor to all of the elements in the array. Since this example is very simple, it only includes one element and one visitor at a time, and so the array will only contain a single element. However, because of the ObjectStructure class, you can add more elements if needed. (The following sections show more detail on how double-dispatch works and how the visitors are implemented.)
Continue reading ‘PHP Visitor Design Pattern II: The Double Dispatch’

Share

PHP Visitor Design Pattern I: The Single Dispatch

visitorTime to Add an Operation

I’ve always liked the Visitor Pattern, but it can appear somewhat daunting from the looks of the pattern’s class diagram. However, by easing into it, it’s fairly manageable and quite useful. In a nutshell, the Visitor allows developers to create programs that perform operations on elements in an object structure without changing the classes subject to the operation. In some respects this sounds a lot like the Decorator pattern but instead of adding properties, the Visitor pattern “visits” the structure with required operations.

Where the visitor comes into play is when you have a set of objects that share a common interface, but some–just some–need a method that does something not part of the interface, but it should not disrupt the interface or the related objects that do not need the method’s operation. In situations where added requirements crop up for extant structures, the Visitor is a welcomed guest.

An Element and a Pretend Visitor

To get started, instead of looking at the class diagram for the whole pattern, I want to take the Element interface and two concrete implementations of that interface as a point of departure. This particular set of concrete Element implementations create shapes using SVG graphics. One implementation creates a circle and the other a a square. Click the Play button to see what the program does and the Download button to view the files:
PlayDownload

A visitor object is one that adds an operation to an existing object without changing the object in the context of its interface. This first implementation assumes that the developer just wanted to make shapes and did not want to add fill color; so the fill color attribute of the SVG element has been left blank. (If no value is entered in the color attribute, it defaults to black–more on that later.)

In order to to show how a blank color is filled, the two shape-making implementations (Circle and Square) have a “pretend visitor.” The “visitor” is nothing but a private method that adds color. It is instructive insofar as it illustrates how to create an operation to add color to an existing method within a class.

First, take a look at the Element interface (IElement). It contains a constant with an immutable state and two methods; one for returning an object and the other the “pretend” visitor” supplies color to an otherwise colorless shape.

 
interface IElement
{
    //Constant for mutually shared code
    const SVG ="<svg width='2.2cm' height='2.2cm' viewBox='0 0 220 220'>";
    //Return object
    function showShape();
 
    //Pretend visitor
    function doColor();
}
?>
</svg>

Next, two implementations of the IElement create Square and Circle classes. Importing the SVG element from the IElement interface (stored as a constant), each class simply returns the code for the requested shape.

//Square.php
< ?php
class Square implements IElement
{
    public function showShape()
    {
        $squareShape= IElement::SVG . "<rect x='1' y='1' width='200' height='200' fill='{$this->doColor()}' stroke='blue' stroke-width='1' />";
        return $squareShape;
    }
 
    //Pretend visitor
    function doColor()
    {
        //pretent visitor red
        return "#b00";
    }
}
?>
 
//Circle.php
< ?php
class Circle implements IElement
{
    public function showShape()
    {
        $circleShape= IElement::SVG . "<circle cx='110' cy='110' r='100' fill='{$this->doColor()}' stroke='blue' stroke-width='1' />";
        return $circleShape;
    }
 
    //Pretend visitor
    function doColor()
    {
        //pretent visitor green
        return "#0b0";
    }
}
?>

The pretend visitor is the doColor() method. It acts like a coloring operation that is coming from “somewhere else.” Subsequent posts examine how a real visitor works, but for now, just take a look at how an outside operation is used to establish color in the showShape() method. (Continue to learn about the roles of the Client and Single-Dispatch.) Continue reading ‘PHP Visitor Design Pattern I: The Single Dispatch’

Share

PHP Functional Programming Part III: λ Lambda Calculus

lambdaCalcλ After learning how to program in Haskell, a pure functional programming language, in the edX course offered through TU DelftX I’m convinced more than ever that to do decent functional programming, you need to understand lambda calculus. I’m not saying that you need to master lambda calculus, but you need to understand it insofar as it applies to functional programming and differentiates imperative programming (what we do in sequential, procedural and OOP with PHP, Java, JavaScript, C++, and C#) and functional programming based on lambda calculus. In this post, I’d like to ease into lambda calculus and illustrate how it applies to functional programming in PHP.

It’s Not Like Other Programming Languages

A typical value a programmer may want to generate for a business site is the cost of an item plus shipping charges. By way of example, suppose that the shipping charges are all 11% of the cost of the item. You might write something like the following:

$priceNship = 14.95 + (14.95 * .11);

That’s not especially useful since you need to have a separate set of literals for each item to enter into the variable $priceNship.

You’re most likely to set up a method that handles such calculations with a variable generated through an argument. For example, you might have a class that looks like the following class and method:

<?php
class RetailStore
{ 
    private $priceNship;
 
    public function addShipping($x)
    {
        $this->priceNship = $x + ($x * .11);
        return round($this->priceNship,2);
    }
}
$worker = new RetailStore();
echo "Cost plus shipping: $" .  $worker->addShipping(14.95);
?>

I used the $x identifier for the parameter for the addShipping() method instead of something more descriptive like $cost because you’ll often see an x-named variable in lambda calculus.

Casting in Lambda Calculus

When using lambda calculus, one of the key characteristics that I had problems getting used to in Haskell was what you might call stating a problem or abstracting a problem. The problem statement is an abstraction of the problem you want to solve using functional programming. Because lambda calculus strives for abstraction, we’ll start with a simple one:

λx.x + (.11 (x))

What does that mean? First of all λx denotes a lambda function. The x variable is bound to the λ function. (It’s known as a bound variable as opposed to free variables. This post deals with bound variables only.) Put into a PHP class and methods, and setting up a return routine, you have the following:

?php
class RetailStoreFunc
{    
    public function addShipping($x)
    {
        // λx.x + (.11 (x))
        $priceNship = function ($x) {return $x + ($x * .11);};
 
        //Round off to 2 decimal points and return
        return round($priceNship($x),2);
    }
}
$worker = new RetailStoreFunc();
echo "Cost plus shipping: $" . $worker->addShipping(14.95);
?>

The λ function (lambda function) shows that the x value is added to the result of .11 times the value of x. In PHP, a λ function is the same as an anonymous or unnamed function. Now, looking at the PHP version of the λ function, you can see:

λx.x + (.11 (x)) = function ($x) {$x + (.11 *$x);};

If you compare the λ calculus with the PHP function, you can see that while the PHP function is a bit less abstract than the λ calculus expression, they are almost identical. Think of the λ calculus as nothing more than an abstraction of a solution.

If you can understand these introductory elements of λ calculus as applied to PHP, not only are you on the path to understanding λ calculus but also PHP functional programming. It’s not as difficult or large as other calculi; so, rest easy and continue.

Functions within Functions

Not only can λ functions return calculated values, they can return other λ functions. So, if you build one λ function, you can use it in another λ function. In this way you can build functional programs. Further, I have not found any contradiction between λ functions and functional programming and OOP in PHP. This next example shows another example of a λ functions in an OOP context, but unlike the first one this one 1) incorporate and returns one λ function in another, and 2) uses a private variable. You cannot assign a λ function to a variable that is not local (part of the method), but you can assign a non-local variable (e.g., private, public or protected) to store the results of a λ function—just not the λ function itself.

<?php
class RetailStoreReady
{    
    private $final;
    public function addShipNtax($x)
    {
        // λx.x + (.11 (x))
        $priceNship = function ($x) {return $x + (.11 * $x);};
 
        // λx.λx + (.07 (x)) (λx. $priceNship(x) + .07 (x))
        $totalWithTax = function ($x) use ($priceNship) {return $priceNship($x) + (.07 * $x);};
 
        //Using an embedded property ($final) for storing results
        $this->final=round($totalWithTax($x),2);
        return $this->final;
    }
}
$worker = new RetailStoreReady();
echo "Cost plus shipping and tax: $" . $worker->addShipNtax(14.95);
?>

In PHP, employ the use statement when one or more λ functions are within a λ function. To employ more than a single λ function within another λ function, you can separate the λ functions by a comma in the use statement as the following shows:

function ($x) use ($lambdaA, $lambdaB) {return $lambdaA($x) + $lambdaB($x);};

The ability of PHP to incorporate these functional programming elements indicates the commitment the PHP community has to functional programming.

Do You Really Need λ Calculus to learn Functional Programming in PHP?

If you read Simon Holywell’s book Functional Programming in PHP, you will find mention of λ calculus, but only a mention. Indirectly, there are some examples, and I found that some basic understanding of λ calculus is very helpful. But λ calculus is not a requirement for functional programming in PHP or any other language. However, if you do understand something about λ calculus, it is extremely helpful to better grasp functional programming in virtually any programming language. In future posts on functional programming, I will be introducing more elements of λ calculus that pertain to better understanding and using functional programming in PHP.

Share

State Maze Part 2: Play

maze2PHP Game Mechanics

In Part I of this “State Maze” series, you see that each cell in the matrix is a coordinate on a grid, and using the alphanumeric coordinate designation, each implementation of a state interface (class) is named with a grid coordinate. (If you have not looked at Part I, do so now.)

The problem with using an HTML UI (See Part I) is that each time the player makes a move, it generates a new instance of the client that makes the move in the State pattern. As a result, I had to create a Json file to store each move. This solution still does not allow the same instance to be re-used and keep a running record of where the player is, but I haven’t found a satisfactory solution elsewhere. (I’m looking at Ajax and RESTful APIs, but nothing yet.) If you’ve developed games with ActionScript (of Flash fame) or Python, you can easily keep a running record in a class property without re-instantiaing the class in a variable. Ironically, by placing the HTML code in a PHP heredoc string, the class with the HTML in it does not have to be re-instantiated, but the client it launches does. To get started, go ahead and play the maze-game and explore the different OOP and Design Pattern principles and languages that use OOP. You will be asked to provide a “seeker” name. The default name is “chump.” Don’t use that name! (Don’t be a chump…) Use a 5-letter name of your own. It will be used to track your progress through the maze.

PlayDownload

This is not an easy maze (nor does it follow the route of the maze in Part I.) So, keep track of your moves, and if you fall into a sequential trap, you have to start over.

State Overview

If you review the State design pattern, especially the class diagram in Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (AKA “The Gang of Four” or GoF) you will see that the Sate pattern consists of Context, State Interface and Concrete States implementing the State Interface. In other words, it’s one of the least complex-looking patterns among design patterns.

Figure 1 shows a file diagram of the current implementation; however, the additional files beyond the basic pattern implementation are files with helper elements for CSS and Json.

Figure 1: File Diagram

Figure 1: File Diagram

With a maze, the State design does require a lot of files — one for each state, and some would prefer a table look-up for dealing with a maze-type application. However, a table look-up has its own issues, and making changes and adding actions can tie a table in a knot. Besides, it’s much easier to re-use a state pattern by changing the method calls within each state without even having to change the context or client at all. Further, since all of the states implement the same interface, once one implementation is completed, it can be copied and pasted, changing only the name of the class and the behavior of the implemented methods defined by the interface. As can be seen in Figure 2, the State pattern used in this implementation adheres to the fundamentals of the State Design Pattern as proposed by GoF.

Figure 2: State Class Diagram

Figure 2: State Class Diagram

Each of the state implementations are designated A1State to E4State. (See the labeled grid in Figure 2 in Part I). Of course, while the State design pattern diagram is relatively simple, the Context can be challenging, especially when using a Json file for recording moves. However, to get started with the code, we’ll start at the beginning with the UI and the Client that makes requests to the State pattern.

The UI and Client

The UI is an HTML5 document embedded in a PHP class and is more of an HTML document than a PHP one. A heredoc string (EXPLORE) is placed in a PHP private variable, $explorerUI. An echo statement displays the HTML on the screen when the $worker variable instantiates the PHP class.

< ?php
class ExplorerUI
{
    private $explorerUI;
    public function __construct()
    {
        //Use the Security object to encode table
        $this->explorerUI=< <<EXPLORE
        <!DOCTYPE html>
        <html>
        <head>
            <link rel="stylesheet" type="text/css" href="explorer.css"/>
            <meta charset="UTF-8"/>
            <title>OOP Cavern</title>
        </head>
 
        <body>
            <h2>OOP Explorer</h2>
        <h3>Explore Next Direction</h3>
        <fieldset>
        <legend>Move Options</legend>
        <form action="ExplorerClient.php" method="post" target="cavestate">
        <table>
            <tr><td></td><td><input type="radio" name="move" value="northMove"/>&nbsp;Move North</td><td></td></tr>
            <tr><td><input type="radio" name="move" value="westMove" checked="checked"/>&nbsp;Move West</td><td></td><td></td><td><input type="radio" name="move" value="eastMove"/>&nbsp;Move East</td></tr>
            <tr><td></td><td><input type="radio" name="move" value="southMove"/>&nbsp;Move South</td><td></td></tr>
        </table>
        </form></fieldset><p></p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type = "text" name="seeker" maxlength="5" size="6" value ="chump"/>&nbsp Your seeker name: Five characters; no spaces<p></p>
        <input type="submit" class="submit" name ="makemove" value ="Make your move"/>
 
        <p></p>
        <iframe seamless name="cavestate" width="500" height="450">CaveState</iframe>
        </body>
        </html>
EXPLORE;
        echo $this->explorerUI;
    }
}
$worker=new ExplorerUI();
?>

I used a table for setting up the UI “move center” to make it easy for the player to select the next move. (A CSS form for the move center certainly would be more elegant, but the table worked ok; so I used it after testing it on a desktop, tablet and smartphone.) You can see how the UI looks in Figure 1 in Part I of the State maze).
Continue reading ‘State Maze Part 2: Play’

Share

The Design Pattern Principle Maze Part 1: A Story in a State Pattern

Happy New Year Everyone!

mazeFor the last ten weeks I’ve been learning functional programming and Haskell through an edX MOOC offered through Delft University (DelftX) in the Netherlands. (TU Delft is The Netherland’s equivalent to MIT in the US) Check out the YouTube video on the course here. That’s why I haven’t been creating new posts for this blog. Now it’s time to catch up! So, I’ve created a maze game that explores the major principles in design pattern programming using a State design pattern.

Play with a Purpose

This particular maze follows a trail of OOP and Design Pattern principles to the end of the maze. As you find each principle, you will see an image and a statement of the principle. For example, the first part of the maze moves through the S.O.L.I.D. acronym to help you remember five basic OOP principles. When you find the room with the Interface Segregation principle, Figure 1 shows what you will see:

Figure 1: A room in the maze with an OOP principle.

Figure 1: A room in the maze with an OOP principle.

Movement is controlled by a set of four ratio button and a “Make Move” button. Each user must include a unique user name where the moves for the user are stored in a Json file. A State Design Pattern helps not only in creating this maze, but it is a template for any 5 x 5 maze!

Why use a State Pattern on a Maze?

In building a D&D style maze, I started out with a blank sheet of paper and sketched out a 5 x 5 maze shown in Figure 2 (with labels).

Figure 2: The 5 by 5 Matrix --  coordinate values will become class names.

Figure 2: The 5 by 5 Matrix — coordinate values will become class names.

By picturing the matrix as being made up of 25 different states, the reason for using a State design pattern starts to take shape. If each grid square is a state, we can create code that determines what happens to the player who moves into a given state (square).

Adding Start/Finish Points and Trouble

You can decide which states will be the starting and ending states simply by designating them as such. As you can see in Figure 3, the game starts in B1 and ends in D5. The next step is to add back-to-the-start traps. These represent any kind of booby-trap you care to add to make the game interesting. You want to add enough to make the player pay attention but not so many as to make it impossible. Figure 3 shows six sequential traps–game re-start conditions that must be avoided.

Figure 3:  Add start and end states and booby-traps.

Figure 3: Add start and end states and booby-traps.

In building your maze, keep in mind that for the player, it will seem like a cavern; not the chessboard that you can see. Continue reading ‘The Design Pattern Principle Maze Part 1: A Story in a State Pattern’

Share