Archive for the 'Encapsulation' Category

Simple Functional Sniffer & Switch Alternative

mix Because PHP is a server-side language, you will have times that you need to rely on client-side languages like CSS, JavaScript and even HTML5 to accomplish certain tasks. In developing the CMS, I realized that while incorporating JavaScript, CSS and HTML5 in heredoc strings, I’d established a barrier between PHP and everything else by only allowing these other languages to interact with PHP through objects. Of course, this is because PHP has emerged into an OOP language and the others have not.

What I failed to take into account is the fact that it’s perfectly possible for OOP structures to interact with non-OOP structures. To some extend that has been done with HTML/CSS UIs and PHP design patterns in several examples. That seems to work out fine, but where you want to use dynamic variables for more responsive HTML pages, we’re back to encapsulating HTML (along with Javascript and CSS) into heredoc strings in PHP. There’s nothing wrong with that, and there’s much to be said for having a fully integrated OOP design pattern with a pure PHP engine.

A Simple Functional JavaScript Sniffer

The problem I discovered in a pure PHP design is that other design possibilities are overlooked. The primary style tool for HTML documents is CSS, and the media queries in CSS3 are designed to be responsive to different devices—namely, those brought about by mobile computing. Sometimes (and I do mean sometimes) that solution seems to work fine. Other, times, however, the media queries fail to capture that chunk of CSS3 code that formats for the desired device. On top of that, it can be difficult calling up certain jQuery mobile files—or any other files—from CSS alone. In many ways, libraries in jQuery have proven to be far more robust than CSS3 alone and far easier to deal with. In several respects, probably in most, neither CSS nor jQuery mobile are programming so much as they are styling tools. As such, they’re the tail of the programming dog. This is not to say they’re less important; they’re just not programming.

So, to sort out the devices looking at our pages, (moving away from CSS media queries) is a programming task. In several other entries on this blog, I’ve looked at ways to sniff through the possible devices, and I think we need to conclude once and for all that user-agents are next to useless. So, by exclusion, we’re left with screen width. So,begin by looking at this simple JavaScript sniffer using two lambda functions:

?View Code JAVASCRIPT
//Save as file name "jsniff.js"
var wide = screen.width;
var beta=function() {wide >=900 ? window.location.href="Desktop.html" :  window.location.href="Tablet.html";};
var lambda=function() {wide <= 480 ? window.location.href="Phone.html" : beta();};

In past posts I’ve used the Chain Of Responsibility (CoR) design pattern to do the same thing using either user agents (forget about it!) or width determined by a JavaScript object. The little JavaScript lambda functions do the same thing, and while at some point of granularity your may wish you had your CoR pattern, generally, I think that there’s enough with the three general categories at this point in time to deal with multiple device. Use the buttons to test the functions. (Try it with your phone and tablet too.) Click PlayA for the sniffer and PlayB for the PHP functional alternative to the switch statement. The download button downloads the source code for both.

PlayAPlayBDownload

The process is pretty simple both from a programming and a lambda calculus perspective. From lambda calculus we get following definitions of true and false:

true := λx.λy.x
false := λx.λy.y

As algorithms, we might consider the following:

function(x, y) {return x;};
function(x, y) {return y;};

So, that means:

function (10,20) = 10; ← true : Is 10
function (10,20) = 20; ← false : Not 10

That’s not exactly lambda calculus, but it’s along those lines that we can eke out an idea. (If you’re thinking, “What about function(10,10) that would appear to be both true and false,” you see what I mean.)

So now we’ll add the values a and b and reduce it:

((λx.λy.x) a b) -> ((λy.a) b) -> a

That replaces λx with (λy.a) b and then a. So a is a. Well, it sounds true!

Then for false we have:

((λx.λy.y) a b) -> ((λy.y) b) -> b

In looking at this, we see that if a is a its true; otherwise it’s b which is not true. That’s pretty much like if-then-else. If true a, otherwise it’s b.

So the line in JavaScript would be a ternary:

lambda = function(a) { return a ? a : b ;};

as well as in PHP,

$lambda = function($a) { return $a ? a : $b ;};

For now, that’s enough linking up lambda calculus with Internet languages. With our JS “sniffer” using a simple HTML call, we can get the page configuration we want for our device based on the window size:

<html>
	<head>
		<title>Functional Sniff</title>
			<script src="jsniff.js"></script>
	</head>
	<body onload=lambda()>
	</body>
</html>

Try it out. It’s easy to write and it’s practical. What’s more, you can see how close everything is to a Boolean type decision. (The different device HTML5 files are in the materials in the download package; one of which uses the jQuery Mobile formatting.)

I Don’t Need No Stinkin’ Switch Statement

One of the nice things about functional programming is that it made me re-think how I was programming. One of the areas where I thought I’d be able to boil down an algorithm to something more compact came when I decided to break down a calendar output into four weekly segment. Using a jQuery calendar, I could pick a day and pass the information to a PHP class for processing. Initially, the switch statement came to mind as a solution in something like the following:

$d=$this->numDay;
switch ($d)
       {
         case ($d >=1 && $d<=7):
            return "jquery";
            break;
        case ($d> 7 && $d<= 14):
            return "haskell";
            break;
        case ($d> 14 && $d<= 21):
            return "php";
            break;
        default: return "racket";
       }

In looking for a range, each case acts like a little function. So why not use lambda functions in PHP to do the same thing. Each query (case/function) either returns a value or goes on to the next case. Here’s what it looks like:

$gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
$beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
$lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
return $lambda($this->numDay);

The last used lambda function is the first in the list ($gamma). That’s because in order for the subsequent function to call them with the use statement, the function used must be defined before the one using it. In functional programming, the use of one function by another is referred to as a closure.

The Language Mix-Master

With the key parts in place, take a look at the different parts and languages used. First of all, the program begins with an HTML5 UI. It links to the jQuery UI JavaScript files and the CSS files. A further stylesheet links to the local CSS.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
   <link rel="stylesheet" href="lang.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>
  <h2>Language of the Week</h2>
  <h4>Click in the text box to select from pop-up calendar: </h4>
 <form action="LangWeek.php" method="post" name="useUI" target="showpix">
<p>Date: <input type="text" id="datepicker" name="pick" /></p>
<input type = "submit" value="Get Language" />
</form>
 <iframe name="showpix" width="300" height="300"></iframe>
</body>
</html>

A form links to a PHP file where it passes the selected datepicker() value. The iframe tag provides a visual feedback embedded in the HTML page. (Note: Remember, with HTML5, iframes are no longer evil.)

Finally, using a single PHP class, the selected date is reconfigured to an integer and evaluated by the lambda functions described above in lieu of a switch statement:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
 
class LangWeek
{
    private $dateNow,$dayMonth, $numDay;
 
    public function __construct()
    {
        $this->dateNow = $_POST['pick'];
        $this->dayMonth=substr($this->dateNow, 3,2);    // Start 03  : 2Length
        $this->numDay = intval($this->dayMonth);
        echo "<img src='images/{$this->chooseLanguage()}' . '.jpg'>";
    }
 
    private function chooseLanguage()
    {
        $gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
        $beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
        $lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
        return $lambda($this->numDay);
    }   
}
$worker = new LangWeek();
?>

Fortunately the jQuery date picker passes the date as a consistent string mm/dd/yyyy, and so the only requirement is to use a substring to find the day of the month and convert it to an integer. This is passed to the chooseLanguage() method that employs the lambda functions.

Mixing it Up

While this blog is dedicated to PHP Design Patterns and their application, I believe that PHP programmers should explore beyond OOP and try out different kinds of programming within an OOP framework, which happily exists within a Design Pattern. The willingness to explore and experiment keeps programming fresh and interesting in any language.

Share

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.

<?php
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:

<?php
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.

<?php
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:

<?php
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.

<?php
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.

<?php
//Helper class
class Move
{
   private $velocity;
   private $capacity;
 
   public function setVelocity($speed,$ship)
   {
      $this->velocity=$speed;
      $this->capacity=$ship;
 
      $ship =<<<SHIP
      <!DOCTYPE HTML>
      <html>
         <head>
         <script type="text/ecmascript">
           // Single global variable
           var photon = 0; // Photon torpedo x position.
 
           function drawSVG()
           {
             //Interval Timer loop
             moveLoop = setInterval(fireTorpedo, $this->capacity);
           }
 
           function fireTorpedo()
           {
             // Change the photon torpedo's position
             photon += $this->velocity;
             photon = photon % 500;
             phpton.setAttribute("x", photon);
           }
         </script>
         </head>
           <body onload="drawSVG()">
             <!-- Create the SVG galaxy. -->
             <!--<?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"> 
               <svg width="500" height="200" viewBox="0 0 500 200"
                  xmlns="http://www.w3.org/2000/svg" version="1.1">
                 <desc>Oopz</desc>
 
                 <!-- Show outline of 2D Galaxy using 'rect' element -->
                 <rect x="0" y="0" width="500" height="200"
                     fill="navy" stroke="blue" stroke-width="1"/>
                 <!-- Space craft Oopz -->
                 <rect x="100" y="100" width="30" height="20"
                     fill="yellow" stroke="#369" stroke-width=".4" id="phpton" />
               </svg>
               <audio autoplay>
                  <source src="photon.ogg" type="audio/ogg">
                  <source src="photon.mp3" type="audio/mpeg">
               </audio>
       </body>
       </html>
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.

Share

PHP OOP: Encapsulating & Communicating with JavaScript and HTML5

EncapDocCan We Talk?

The initial discussion of the Memento design pattern illustrated how a state could be saved in a different object than the one in which the state originated. A Caretaker object holds the saved state and when requested, it returns the state to the Originator, all without breaking encapsulation. A practical example of employing the Memento that comes to mind is where the user is looking through a list. As she goes through the list, she sees different items (flowers in this case) that she is considering. However, because it’s a long list, she cannot remember which one she likes; so she tags those she is considering. After going through the whole list (all of the different flowers), she can easily recall those that she had tagged–recall them from a Memento. Play the little app and download the source code before going further:
PlayDownload

Communicating with HTML and JavaScript

Working HTML and JavaScript into PHP is no great shakes, and most PHP developers probably have done so at one time or another. However, most of the time I find myself creating horrible mixes of code for a one-off use with nothing encapsulated. The goal here is to see how everything in the application can be encapsulated and at the same time communicate. The purpose here is to find a single state variable that is used by HTML, JavaScript and PHP. Further, that state must be available for placing into a Memento object and stored for later use. (This post simply examines one way to encapsulate everything and have them communicate; however, material from this post will be used in developing a Memento example in a future post.) Also, I wanted to import all of the JavaScript and CSS separately. Figure 1 shows the general plan. (The ‘gardner’ folder contains the flower JPEG images.)

Figure 1: Encapsulating JavaScript, CSS and HTML into EncapDoc PHP class

Figure 1: Encapsulating JavaScript, CSS and HTML into EncapDoc PHP class

The CSS is just the stylesheet and it contained no functionality that you often find when it is used in conjunction with jQuery. I needed the JavaScript for clicking through the images. Had I swapped images using PHP I’d probably have to reload an HTML page with every swap and that seem prohibitively expensive. So I wrote the most simple JavaScript swap program I could think of with two functions for swapping and an added JavaScript function to get the initial starting picture (an integer value) passed from PHP. The following JavaScript listings shows how simple the script is:
Continue reading ‘PHP OOP: Encapsulating & Communicating with JavaScript and HTML5’

Share

OOP PHP III: Properties and Variables

oop3From Variable to Class Property

All classes in all programming languages are made up of two fundamental elements, 1) Methods and 2) Properties. In this installation of learning OOP in PHP, I want to look at properties.

To understand properties in a PHP class, it’s important to understand (at this stage) that we’re dealing with variables. Variables inside of a class can act as properties of that class or properties of a method within a class. In OOP, we speak of visibility of variables/properties. You will find an earlier post on this blog that explains private variables in detail, and future posts delve into visibility in greater detail. For now variables in PHP (and virtually every other programming language) have two basic types:

  • local
  • global

Generally speaking any variable declared outside of a function in a sequential or procedural listing is global, and any variable declared inside of a function is local. The same is true to some extent in OOP programming, but variables (or properties) require a different sense. Take a look at the video, and you’ll see the basics of variables within classes.

The video touches on the most fundamental aspects of variables and properties. However, as every PHP programmer knows, there’s no substitute for some clear practical OOP PHP code. The following examples show several different aspects of creating and using variables and properties.

All of these examples use a Client->Request->Class model. The first is similar to the one in the video except it has a client make the request:
Client 1
Client1

<?php
//Client1.php
include_once('OneProp.php');
class Client1
{
 
        public function __construct()
        {
            //$oneProp is a local variable
            $oneProp = new OneProp();
            echo $oneProp->showProperties();
        }
}
//$worker is a global variable in this program
$worker = new Client1();
?>

OneProp

<?php
//OneProp.php
class OneProp
{
        private $magicWord;
 
        public function showProperties()
        {
            $this->magicWord = "<h1> Alacazam! </h1>";
            return  $this->magicWord;  
        }
}
?>

More Properties and a Little JavaScript inside PHP Class

This last example is a little more involved. One of the properties is assigned an entire Web page using heredoc. Two more properties serve as labels and instructions. Here we use a little JavaScript, and the JavaScript event handler (onClick) uses the this statement and property reference using a dot:

this.src

Because the JavaScript is part of a heredoc string in a PHP property ($this->document), PHP does not attempt to execute the JavaScript or find an error in its format. (In other words it doesn’t throw an error when this.src appears instead of $this->src is in the JavaScript listing.)

Client2

<?php
include_once('ImageSwap.php');
class Client2
{
        private $light;
        public function __construct()
        {
            $light = new ImageSwap();
        }
}
$worker = new Client2();
?>

ImageSwap

<?php
//ImageSwap.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
class ImageSwap
{
    private $document;
    private $turnOff;
    private $howTo;
 
    public function __construct()
    {
        $this->document = <<<LIGHTSWITCH
        <!doctype html>
        <html>
        <head>
        <meta charset="UTF-8">
        <script>
            var onImg= "on.jpg";
            var offImg= "off.jpg";
        </script>
        <title>Light Switch</title>
        </head>
        <body>
        <img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>
        </body>
        </html>
LIGHTSWITCH;
        $this->turnOff = "<h3>Turn off the light!</h3>";
        $this->howTo = "<h4>(Just click the image!)</h4>";
 
        echo $this->turnOff;
        echo $this->document;
        echo $this->howTo;    
    }
}
?>

To run this, you’ll need to download the following two graphic files:
onoff

Put the two graphic files into the same directory as the classes you’ll be using. Notice how the three different properties in the ImageSwap class are employed. Also note that in the two Client classes, the $worker variable (not a property because it does not belong to a class) is assigned an object. To download the two graphic files, just right click to download them and then move them to the same directory (folder) with your ImageSwap.php file. In the next installment of OOP PHP, we’ll look at the visibility that properties and methods can have and how to use them.

Share