Archive for the 'Loose Coupling' 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 Bridge Pattern CMS

bridgeCMSA Flexible CMS

The previous post on the PHP Bridge Design pattern shows how a Bridge pattern has two connected but independent interfaces to make design flexibility for different online devices. This post explores how that same flexibility extends to making a Content Management System (CMS). Most of the Bridge participants in the design are unchanged or only slightly changed.

The major change in the Bridge design pattern actually makes it more in line with the original intention of the Bridge. The RefinedAbstraction participant (RefinedPage) no longer includes concrete content for the page. Instead, it provides the parameters for a client to add the content. This change adds flexibility and gives the developer more options than the original StandardPage class.

Two UIs and Multiple Clients

In order to make a decent CMS, you need to have at least two UIs:

  1. An Administrative UI for previewing and adding new content
  2. A User UI for viewing but not changing content

In creating the Administrative UI (HTML5/PHP/JavaScript), I had to use two PHP clients. One client is to preview the new data entered by the admin and the other client is to store the new data (after previewing and possibly editing it). Figure I provides a general overview of the UIs and the Clients that will use the Bridge pattern for a CMS:

Figure 1: User Interfaces and Clients

Figure 1: User Interfaces and Clients

The Administrative UI (BridgeCMSAdmin.html) uses the BridgeCMSAdminClient class for displaying different content and the StoreDataClient class for storing the information in a JSON file. An important condition to remember is that when using JSON files, you need to make their permissions available for reading and writing. (See the Memento II post and the special mini-post on setting permissions on Raspberry Pi systems.) Thus, the need for two clients; one for previewing new material and another for storing it in a JSON file. A lot of files are involved in this CMS; so take a look at the two different UIs and download the files for everything:
PlayPlayAdminDownload

To use the Administrator Module, follow these steps in the listed order:

  1. Type in Header data, select a graphic from the drop down menu, and then type in text for the body.
  2. Click a Desktop, Tablet or Phone radio button and then click Preview Page
  3. When you have everything the way you want it, First click Transfer to Storage and next click Store Data
  4. Now click the Play button and see the page you created.

In the admin UI, I used a drop down menu with only three selections for the graphic file since only three were set up. However, it would not be difficult to upload graphics and their file names. (See the post on uploading graphics using the Template Method.)

The UIs and their Clients

The main feature in creating a CMS is the Administrative UI. It calls two different clients for dealing with previews and persistent data storage. Unless you’re planning on a fairly long body text entry, the JSON file works fine. Look at the code below, and you can see that one of the issues is that the data that is entered for the preview must be transferred to a different form. It transferring the data is a simple task with a little JavaScript. The following script is all it takes:

?View Code JAVASCRIPT
function transferData(formNow)
{
    formNow.header.value = bridgeWork.header.value;
    formNow.graphic.value = bridgeWork.graphic.value;
    formNow.bodytext.value = bridgeWork.bodytext.value;
}

Stored in an external JS file, it was used only when the data was going to be stored; however, before storing it, it had to be transferred from the bridgeWork form to the dataStore form.

?View Code HTML
< !DOCTYPE html>


    
    
    CMS Admin Bridge


    

Enter Update Data

 Header

Enter the text for the body below:

Preview New Data

 Desktop
 Tablet
 Phone

 

Store New Data

 

Then using build-in PHP JSON json_encode() method, the data were placed into an array and stored in the JSON file. This was done using the StoreDataClient class:

< ?php
class StoreDataClient
{
    private static $dataStorage=array();
    private static $jsonFile="content.json";
    //Client stores data
    public static function store()
    {
        if (isset($_POST['jsonstore']))
        {   
            self::setStore();
        }
      file_put_contents(self::$jsonFile,json_encode(self::$dataStorage,JSON_UNESCAPED_UNICODE));
    }
 
    private static function setStore()
    {
        //Pushes data from HTML to array
        array_push(self::$dataStorage,$_POST['header'],$_POST['graphic'],$_POST['bodytext']);
    }
}
StoreDataClient::store();
?>

Just in case you’re wondering why a single PHP client class was not used for both preview and storage, it’s simple:

OOP Principle: Each class should have only a single responsibility.

We don’t want to cram classes; so each responsibility has its own class. (Click below to see the other client and the rest of the CMS.)
Continue reading ‘PHP Bridge Pattern CMS’

PHP Strategy Design Pattern Part II: Add a Context

pulp Adding a Context

A few years back, a post on this blog looked at examples of PHP design patterns that had missing parts. In 2006, an IBM sponsored post introduced PHPers to design patterns in “Five common PHP design patterns.” This was an important post because it demonstrated that far from being the exclusive domain of languages like Java, design patterns were applicable to PHP as well. However, of the five patterns, (Factory [Factory Method], Singleton, Chain-of-Command [Chain-of-Responsibility] , Observer, and Strategy) two (Factory and Chain-of-Command) were misnamed and misrepresented, one (Singleton) has since been more-or-less deprecated as a pattern (by no less than Erich Gamma) and the other two were iffy in their implementation.

Like lemmings following each other over a cliff, PHPers often followed each wrong example, further perpetuating the ill-formed pattern. So, when we look at patterns, lest PHP programmers be considered rank amateurs, we need to get patterns right. One of the most common mistakes with the Strategy pattern is either ignoring or leaving out the Context class altogether. In Part I of this two-part series, we saw what a Near-Strategy pattern looks like without a Context class. In Figure 1 of that same post, you can see the class diagrams of the Near-Strategy and Strategy patterns. The example in this post is of a correctly formed Strategy pattern. Play the Strategy example and Download the files with the following two buttons:
PlayDownload

The Context Participant

To get the Context right, we need to go to the original source, Design Patterns: Elements of Reusable Object-Oriented Software. The Context participant has the following characteristics:

  • Configured with a ConcreteStrategy object
  • Maintains to reference to a Strategy object
  • May define an interface that lets Strategy access its data

At the heart of the Strategy design pattern, the Context and Strategy interact to implement the selected algorithm in the form of a concrete strategy. The key here is,

The Strategy lets the algorithm vary independly from clients that use it.

In order to do this,

A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively.

Figure 1 shows the path used in this implementation:

Figure 1: The path through the context to request an algorithm (concrete strategy)

Figure 1: The path through the context to request an algorithm (concrete strategy)

The path begins with the Client creating an instance of a specific concrete strategy (received from the HTML UI) and using that instance as a parameter to make the request through the context. From this point on, the client no longer is in contact with the strategy but instead the context. The context takes the instance passed from the client and makes the request through the strategy interface [algorithmInterface()]. Any client can make similar requests through the context by passing the concrete strategy through its context interface. That can be very handy when your program has more than a single client requiring a strategy.
Continue reading ‘PHP Strategy Design Pattern Part II: Add a Context’

PHP OOP Game Coding: Collision Detection

ropeDistance in 2D Space

For a number of years I’ve had David Bourg’s book, Physics for Game Developers (2002, O’Reilly), and I’ve been meaning to translate a set of formulas into OOP classes that could be used as part of a PHP game development library. After spending time on (simple) game development last summer using Python, I decided it was time to get busy with a similar project using more OOP and PHP. I wanted something that was small enough to run on Raspberry Pi computers, but still an animated video game.

On previous posts on this blog I’ve used SVG graphics with PHP, but the examples I used were fairly static. Here I’d like to try them in a more dynamic role to see if PHP could generate code to make them dance. For starters I thought that a simple 2D space game would be appropriate — more on the order of Astroids than Space Aliens.

2D Outer Space on a Grid: Plane Geometry

In order to get anywhere, I decided that the universe (galaxy, solar system, whatever; you choose) would live on a 500 x 400 grid. It can be adjusted for different screens, but the first step is to set up a common grid for clear discussion. Further, I thought that starting with rectangles as ‘space ships’ would make everything else easier. (You can build something more elaborate later in the series.) The two space crafts are Oopz and Titeaz. Oopz is crewed by OOP developers, and Titeaz has a crew of sequential and procedural programmers who keep getting in trouble because of spaghetti knots and tight bindings. The Oopz goes on rescue missions to send them PHP code packages of classes and design patterns. Figure 1 shows the initial positions of the two ships:

Figure 1: Grid with Oopz and Titeaz

Figure 1: Grid with Oopz and Titeaz


Each of the grid squares in Figure 1 is 50 x 50 pixels, and the space ships use conventional a x|y position denotation.

Determining Distance and Collision Detection

The first thing we’ll tackle in Rocket Science 101 is determining the distance between two objects.

Raspberry Pi Users: You will need the Chromium browser for the graphics in this series. You can download it using the following code:
sudo apt-get install chromium

The distance between objects can be used for everything from determining when two objects have collided (distance = 0 + fudge-factor) to when another ship is in rescue range to receive project-saving OOP code. The SVG objects on your screen (without the grid) can be seen in Figure 2:

Figure 2: Determining Distance

Figure 2: Determining Distance

The code for this starting screen is based on the SVG W3 standards and saved as an XML file:

< ?xml version="1.0" standalone="no"?>
< !DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
 width="500" height="400" viewBox="0 0 500 400"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
>Oopz and Titaz>

 x="0" y="0" width="500" height="400"
        fill="#DCDCDC" stroke="blue" stroke-width="1">>

 x="100" y="100" width="30" height="20"
        fill="#cf5300" stroke="#369" stroke-width=".4">>

 x="300" y="200" width="30" height="20"
        fill="#369" stroke="#00cc00" stroke-width=".4">>
>

To see the distance calculation, click the Play button. See if you can figure out what formula is used before you look at the code:

PlayDownload

The calculations are based on one of the most fundamental theorems in plane geometry. Before continuing, see if you can figure it out and resolve the solution.
Continue reading ‘PHP OOP Game Coding: Collision Detection’