Archive for the 'SVG' Category

PHP Command Design Pattern: Part I

commandEncapsulate a Request

On occasion when developing an application, you may want to issue a request, but you may not know about the requested operation or its receiver. Imagine that you’re developing a game, and you’re working on a “Commander” (like Captain Kirk of Star Trek). The commander will issue commands, but during development or execution, you’re not sure who’s going to carry out the command or exactly how it’s going to be done. For instance, suppose that a Weapons Officer on the bridge simply pushes a button when the Captain issues a command to fire a photon torpedo. However, suppose that the bridge is damaged and the Weapons Officer wounded and cannot carry out the command. Any decent game designer would allow for someone else to launch the torpedoes; a crew member working in the torpedo bay, for example. Therefore, you would not want to tightly couple the action of firing a photon torpedo with the Weapons Officer. Something like;

weapons_officer->firePhotons()

would not be a good idea. Instead, you’d want the request to be handled by anyone who could get to the torpedoes triggering mechanism—no matter who it was or what triggering device was employed.

The Command design pattern encapsulates the request as an object, and allows you to add parameters to the clients with different requests. You can also support undoable operations—like firing off a photon torpedo! In this particular example, the participants and implementation is quite simple. I employed a helper class (Move) to add a little flair to the example, but otherwise, it’s a very simple implementation of the Command design pattern. Fire off the torpedo and download the files to get started:
torpedoDownload

The movement operations were taken from an earlier post on this blog of working with SVG files—once again illustrating the re-use functionality of OOP design. The helper class, Move is almost wholly a re-use of the earlier implementation. The sound was added to the class for this example.

The Wholly Involved Client

The requesting client is fully involved in the Command pattern. It is associated directly with both the Receiver and the ConcreteCommand classes. Figure 1 shows the pattern’s class diagram:

Figure 1: Command class diagram

Figure 1: Command class diagram

In this example, I employed a single Client, Receiver, Invoker and ConcreteCommand. Largely, I re-purposed an abstract example that Chandima Cumaranatunge had used in ActionScript 3.0 Design Patterns that we had co-authored in 2007—the main difference being that the example is written in PHP and I added an action that involved sound and animation. However, it is largely the same. In looking at the code in the Client, you can see that it creates instances of a ConcreteCommand, Receiver and Invoker.


error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
// Autoload given function name.
function includeAll($className)
{
    include_once($className . '.php');
}
//Register
spl_autoload_register('includeAll');
 
/* Client */
class Client
{
    public static function request()
    {
        $rec = new Receiver();
        $concom = new ConcreteCommand($rec);
        $invoker = new Invoker();
        $invoker->setCommand($concom);
        $concom->execute();
    }
}
$worker=Client::request();
?>

As you can see, the Client, chooses the concrete command and the invoker. Figure 2 shows the file diagram for this Command implementation:

Figure 2: Command file diagram

Figure 2: Command file diagram

This pattern can have different commands and different invokers, but the key lies in the Command interface (ICommand) that includes an execute() method that invokes the command. It doesn’t concern itself with what other object does the invocation; it just provides the interface for some object to carry out the command.Using the bare minimum, the interface has a single abstract method:


interface ICommand
{
   function execute( );
}
?>

The design allows for a number of different ConcreteCommand classes, especially flexible because of the simplicity of the interface. However, in this example, only a single concrete command implements the interface.


class ConcreteCommand implements ICommand
{
    private $receiver;
    function __construct(Receiver $rec)
    {
        $this->receiver = $rec;
    }
    public function execute()
    {
        $this->receiver->action();
    }
}
?>

The receiver has been identified by the Client and passed to the parameterized ConcreteCommand by the Client. The Client acts very much like a conductor in this pattern. It pulls a the pieces together and determines how they will interact together. All of the work is to carry out the command realized in the Receiver class.

The Invoker Makes it Happen

Returning to the Star Trek example where the Captain commands the Weapons Officer to “fire a photon torpedo,” the Weapons Officer is the invoker. That is, by pressing the Fire button, she executes the command. However, as we noted, maybe the Weapons Officer is unable to carry out the order because she has been knocked out in a battle, and so someone else has to do it. Because the command and the invocation of the command are loosely coupled, any available invoker could carry out the command. First, take a look at the Invoker class:


class Invoker
{
    private $currentCommand;
    public function setCommand(ICommand $c)
    {
        $this->currentCommand = $c;
    }
    public function executeCommand()
    {
        $this->currentCommand->execute();
    }
}
?>

Note that both a method for setting the command and one for executing the command are part of the Invoker class. The Client sets the command, but how is it executed? Again, it is the Client, but the execute() method is through the ConcreteCommand instance; also called by the Client.

The Receiver Knows What to Do

In order for the command to be carried out, at least one object needs to do what the command requires. In this case, it’s the Receiver. Following the path so far:

  1. The Command tells what to do.
  2. The Invoker tells an object to carry out the command
  3. The Receiver carries out the requirements of the command.

Keep in mind that all of this is done with loosely coupled objects, and different participants can carry out the different roles.


class Receiver
{
   private $speed;
   private $photon;
 
   public function action()
   {
         $this->speed= 20;
         $this->photon = 16; 
         $launcher=new Move();
         echo $launcher->setVelocity($this->speed,$this->photon);
   }
}
?>

I suppose this is a bit elaborate for an abstract example, but it seemed a little more illustrative with something other than an echo statement that the Receiver object announced. Besides, it illustrates re-use of a class as a helper class for the Receiver to do a bit more. As you can see from Move helper class, a the property IDs from the original use have been retained—e.g., ‘ship’ and ‘torpedo’ used for the same purpose.


//Helper class
class Move
{
   private $velocity;
   private $capacity;
 
   public function setVelocity($speed,$ship)
   {
      $this->velocity=$speed;
      $this->capacity=$ship;
 
      $ship =<<
      
         
         
         
           
             
             
              
               
                 Oopz
 
                 
                 
                 
                 
               
               
       
       
SHIP;
      return $ship;
   }
}

You can revise the actions of the Receiver to virtually anything you want. The important point with the Command class is that the original command (request) is encapsulated through the ICommand interface, and in the development process there can be any number of different requests fulfilled by different receivers and launched by different Invoker objects. Further with added commands, you can also add new invokers and ever receivers.

Beyond Abstract Command Structures

Even though this example has not been quite as abstract as originally planned, it is still pretty basic. What I’d like to do in subsequent examples is to build on this basic pattern where multiple commands, invokers and receivers work in concert through the Command design pattern. In the meantime, feel free to try out some of your own ideas and offer suggestions for further improvement and/or refinement.

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’

The Composite Design Pattern in PHP: Part IV Composite Drawing

killeAppA Composite Drawing Program

In the original Gang of Four Composite example, (pp. 163-173 of Design Patterns) they showed a drawing program. It was broken down into separate leaves for Line, Rectangle, and Text. I included those leaves and added a Circle leaf. On the first rendering, I used .svg files, but that turned out to be far more limited and awkward than I wanted. Since PHP is not known as a language for doing graphics like ActionScript and Python (or Java for that matter), I wanted to use it for a dynamic engine for taking advantage of the HTML5 svg tag. To my surprise (and delight) I found that everything worked quite well with all of the browsers. I still only used subset of the six basic shapes provided in the SVG 1.1 W3 release. Text is considered a separate object apart from the basic shapes of:

  • rectangle
  • circle
  • ellipse
  • line
  • polyline
  • polygon

Before going further, it will help to look at the code and the example of employing the Composite pattern with Scalable Vector Graphics(SVG). Also, your might want to look at Part I, Part II and Part III of the Composite Pattern series on this blog. Use the Play button to see the composite SVG creation and click the Download button to get a zip file with all the code for the application;
PlayDownload

SVG Leaves

This Composite example employs the structure and most of the code from the full pattern example from Part III of this series. The major changes are to the leaf elements and rendering in the Composite. However, not a lot has changed otherwise, and that is one of the essential features of design patterns: re-use. First, take a look at the rectangle leaf class:

< ?php
//Rectangle.php
class Rectangle extends IComponent
{
    private $xpos;
    private $ypos;
    private $wide;
    private $high;
    private $fill;
    private $stroke;
    private $strWidth;
 
    public function __construct($rx,$ry,$rw,$rh,$f,$sc,$sw)
    {
        $this->xpos=$rx;
        $this->ypos=$ry;
        $this->wide=$rw;
        $this->high=$rh;
        $this->fill=$f;
        $this->stroke=$sc;
        $this->strWidth=$sw;   
    }
 
    /* None of this batch of methods are used by shape or rectangle leaf */
    /* However in order to correctly implement the interface */
    /* you need some kind of implementation */
    public function add(IComponent $comOn){}
    public function remove(IComponent $comGone){}
    public function getChild($int){}
    protected function getComposite() {}
 
    /* Draw Rectangle */
    public function draw()
    {  
        echo "";
    }
}
?>
rect>

It does not use most of the inherited abstract classes but implements them because the structure calls for it. The draw() method then sets up the SVG parameters for the rectangle shape. As you will see, the other leaf classes do the same thing in the continuing page:
Continue reading ‘The Composite Design Pattern in PHP: Part IV Composite Drawing’