Monthly Archive for February, 2015

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 . "";
        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’

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 ="";
    //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 . "";
        return $squareShape;
    }
 
    //Pretend visitor
    function doColor()
    {
        //pretent visitor red
        return "#b00";
    }
}
?>
 
//Circle.php
< ?php
class Circle implements IElement
{
    public function showShape()
    {
        $circleShape= IElement::SVG . "";
        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’

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:


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.


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.