Archive for the 'OOP and Design Pattern Principles' Category

Is PHP an OOP Gateway Drug?

gatewayIs OOP in PHP going to Help in Other Languages?

PHP is a great tool for working with both Web-based languages like HTML5, JavaScript, CSS3 and jQuery (actually a kind of JavaScript). Of course it’s an essential tool for working with SQL and the kinds of server-side operations that can only be done with a server-side language like PHP.

With the advent of mobile devices, PHP developers are able to add to help recognize devices through user-agents, but sniffers are plagued by both the vague information provided by the user-agents and may not be able to tell the difference between different screen widths and resolutions with the same user-agent information; like iPads and iPad Minis. Microsoft has the same user-agent id for all of their devices–“trident.”

Web Apps and Device Apps

PHP has been a great tool in Web app (applications that run in a browser) development for mobile devices, but these apps are largely dependent on an Internet connection, and unless there’s some way to add a local host to an Android-based Note or iOS-based iPhone, you rely on a connection to the Web. Even with WiFi being widely and generally available, an app that runs on the native Android OS or the Apple iOS (Device App) has lots of advantages over a Web app.

Don’t get me wrong. Web apps have tons of advantages over device apps when it comes to development and distribution. All devices that have browsers can run Web apps, but apps made for an Android will not run on iOS devices and vice versa.

So if you know PHP (and lots of other Internet languages), at some point you may have to bite the bullet and download the (free) Android and/or iOS SDK (Software Development Kit). The good news is that if you’ve been working with PHP OOP and design patterns, much of the code environment will look very familiar. The IDEs used by both the Android and iOS SDKs are very similar. The development process, though, takes place within classes and structures that you will be familiar with—depending on how much you’ve been experimenting with PHP OOP and design patterns.

For example, the following is a simple Swift class that generates a message—not too dissimilar from what JavaScript does with an alert() function.

?View Code SWIFT
import UIKit
 
class ViewController: UIViewController
{ 
    @IBAction func showAlert()
    {
        let alert = UIAlertController(title: "Sandlight Productions, LLC",
            message: "Messages for the World!",
            preferredStyle: .Alert)
 
        let action = UIAlertAction(title: "Sandlight", style: .Default, handler: nil)
 
        alert.addAction(action)
 
        presentViewController(alert, animated: true, completion: nil)
    }
 
}

Both the Android and iOS SDKs have lots of importable classes, and the imported UIKit has objects for the UI. The class declaration,

class ViewController: UIViewController

would be like declaring

class ViewController implements UIViewController

in PHP. So, while some different operators are used (e.g., : instead of implements) most of the statements are pretty close to those in PHP.

Some, though, are special to both the framework and the language. For instance,

@IBAction func showAlert()

does not have an equivalent in PHP for the whole method. The @IBAction connects the source code to a UI object. The showAlert() method, in this example, is connected to a button in the Interface Builder, part of the iOS SDK. Further, func is used instead of function used in PHP.

In declaring variables, Swift, uses the let keyword and the = assignment operator, and Swift does not use the new keyword in creating objects. For example, in Swift,

let alert = UIAlertController(//parameter list);

would be,

$alert = new UIAlertController(//parameter list);

in PHP. If you understand something about OOP and design patterns, this other type of programming makes more sense than if you do not.

Figure 1 shows the output on a simulator developed in the iOS SDK:

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

In and of itself, it’s no great shakes. However, it can be run anywhere and without a browser or an Internet connection. What’s important is that those working with OOP and design patterns in PHP are far closer to the languages used for Android (Java) and iOS (Swift). So if you start getting clients who demand to have their own apps to be downloaded to their phones and used without a browser, don’t be afraid to start making some simple ones. You can even create a device app that calls up a mobile app written in PHP and jQuery Mobile. The big advantage of that is you can access an SQL database.

Event Driven Programs and Programming: Not So Much PHP

If you’ve ever made a game—especially the arcade type—you’re probably familiar with “event-driven programming.” Languages like ActionScript, including OOP and design pattern designs, used to be used a lot in event-driven software development. The State design pattern is often used for event-driven programs since the states keep changing with new information from the user. The events are typically made up by the user tapping, sliding and dragging objects on the screen. PHP at some base is more of a data-getting and setting type of software. The getting and setting is done in conjunction with MySQL and the SQL language.

A lot of mobile app development is done with event-driven processes, and at least in the SDKs for iOS and Android, the frameworks are set up in classes and more state-like programming than you’ll see in most PHP. However, on this blog, the Client-Request model is easily applicable to event-driven kinds of applications. A number of PHP programmers have some interesting suggestions for event-driven programming and programs, but I’m not sure how well they’d work compared to languages like Python where the connections to the event-producing object (e.g., mouse/finger clicks/taps and keyboard entries) are more direct. PHP is a bit too dependent on HTML and JavaScript to handle events in client-side events.

In any event, using OOP and design patterns in PHP is very transferrable to other languages. The same is true in using the logic and structure of functional programming. So, if you’re thinking about jumping into either iOS or Android app development, you’ve be entering a familiar programming environment if you understand working with OOP and design patterns in PHP. Don’t be afraid of event-driven programs even though they’re not exactly common in PHP. The structures you will work in will be very familiar.

PHP Template Method Pattern: Geolocation Encapsulated

bostonI was invited to speak at on April 22 at Microsoft’s NERD Center in Boston for Month 4 of Boston PHP’s 200 Days of Code. The Advanced track of 200 Days of Coding is going through Larry Ullman’s book, PHP Advanced & OO Programming (3rd ed), and I’ll be talking about materials from Chapters 8-10. However, with a little over an hour, I am using Occam’s razor to keep things focused, pertinent and related to the relevant chapters. Chapter 10 is about Networking with PHP, and by way of preview, I thought I’d take the material that Larry has on geolocation, and put it into an OOP structure using the Template Method design pattern. I also made a number of other modifications for which Larry cannot be blamed! Go ahead and Play the program to see what it does and Download the code. (The text window defaults to sandlight.com but you can add any URL you want.)
PlayDownload

The Magical Template Method

The first thing I did was to set up the geolocation app with a Template Method. You can see previous discussions and examples of the Template Method on this blog, but I wanted to include the class diagram the Gang of Four used to see how simple but elegant this pattern actually is. Figure 1 shows this subtle but powerful method:

Figure 1: Template Method class diagram

Figure 1: Template Method class diagram

The nice thing about this design pattern is that it has lots of uses as you may have already seen on this blog. However, the same simple principle is used: Abstract methods from an abstract class are implemented in a concrete method from the same abstract class. What the Template Method does is to provide a blueprint for the order of the methods to be used with the exact content dependent on the intended use.

So, starting with the abstract class, you can see how this implementation works:

< ?php
abstract class ILocatorTemplate
{
    protected $url, $info, $data, $ip, $loc;
    protected $package=array();
    protected abstract function getLocation();
    protected abstract function bundle();
 
    //The Template Method
    protected function templateMethod()
    {
        $this->getLocation();
        $this->bundle();
    }
}
?>

A number of protected properties are first declared, including an array object, $package. Next the two primitive operations are declared, getLocation() and bundle(). The former is for getting the geolocation of a URL and the second for placing that information into the $package object. That’s it! All that’s left to do is to implement the abstract class.

The Locator class

The concrete implementation of the ILocatorTemplate adds content to the properties and concrete operations to the two abstract methods.

< ?php 
class Locator extends ILocatorTemplate
{
    public function doLocate($place)
    {
        $this->loc = $place;
        $this->templateMethod();
        return $this->package;
    }
 
    protected function getLocation()
    { 
        $this->ip = gethostbyname($this->loc);
        $this->url = 'http://freegeoip.net/csv/' . $this->ip;
 
        $this->info = fopen($this->url, 'r');
        $this->data = fgetcsv($this->info);
        fclose($this->info);
    }
 
    protected function bundle()
    {
        $this->package['IP']=$this->data[0];
        $this->package['CountryID']=$this->data[1];
        $this->package['Country']=$this->data[2];
        $this->package['StateID']=$this->data[3];
        $this->package['State']=$this->data[4];
        $this->package['City']=$this->data[5];
        $this->package['Zip']=$this->data[6];
        $this->package['latitude']=$this->data[7];
        $this->package['longitude']=$this->data[8];
    }
}
?>

The doLocate() method holds the URL passed by the user. That is placed into one of the properties declared in the abstract class, $loc. Next, the $templateMethod() fires and it, in turn, launches first the getLocation() method and then the bundle() method. It doesn’t matter what is in those methods because they were defined abstractly. Therefore, any abstract method defined as part of template method will launch regardless of its implementation, as long as it adheres to the signature form in the abstract class. The getLocation() method pretty much follows the steps Larry lays out in Chapter 10. It uses the freegeoip.net Web service which returns CSV data with the location information.

The bundle() method transfers the data from the $data array send by the Web service into an associative array, $package. The keys in the associative array will serve as labels for the data once processed in the Client class.

The last step in the process is to return the $package containing an associative array with descriptive keys and location information. That’s it….but there is one more thing before we turn to the UI and client.

The Hollywood Principle

The Template Method exemplifies a larger design pattern principle called the Hollywood Principle, simply stated,

Don’t call us. We’ll call you.

It refers to how a parent class (ILocatorTemplate) call the operations of a subclass (Locator) and not the other way around. The templateMethod() function is a concrete method from the parent class, and both the getLocation() and bundle() methods are implementations of the child class, Locator. So, the parent class method calls the child class implementations; not vice versa. This fundamental principle will help keep your PHP OOP from getting tangled up.
Continue reading ‘PHP Template Method Pattern: Geolocation Encapsulated’

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 Caverntitle>
        head>
 
        <body>
            <h2>OOP Explorerh2>
        <h3>Explore Next Directionh3>
        <fieldset>
        <legend>Move Optionslegend>
        <form action="ExplorerClient.php" method="post" target="cavestate">
        <table>
            <tr><td>td><td><input type="radio" name="move" value="northMove"/>&nbsp;Move Northtd><td>td>tr>
            <tr><td><input type="radio" name="move" value="westMove" checked="checked"/>&nbsp;Move Westtd><td>td><td>td><td><input type="radio" name="move" value="eastMove"/>&nbsp;Move Easttd>tr>
            <tr><td>td><td><input type="radio" name="move" value="southMove"/>&nbsp;Move Southtd><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">CaveStateiframe>
        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’

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’

PHP Functional Programming Part II: OOP & Immutable Objects

immutableImmutable

In his book on Functional Programming in PHP Simon Holywell laments the lack of immutable structures in PHP, and while he suggests some hacks to insure immutability, we can make-do with some different hacks I’ll suggest. (Most of the hacks are mind-hacks–a way of thinking about data.) The idea of having a programming language where all objects are immutable (unchanging) sounds pretty awful. Not only that, it sounds impractical. Take, for example, a Boolean. It has two states; true and false. In functional programming, that means the Boolean variable is mutable, and so it’s out. However, you can have two objects that we can call, Alpha and `Alpha. Alpha is true and `Alpha is false. (The tick mark [`] is the key below the ‘esc’ key on your keyboard.) So instead of changing the state of Alpha from true to false, you change the object from Alpha to `Alpha.

Why would anyone want to do that? It has to do with the concept of referential transparency. In a concrete sense it means that if an object (reference) were replaced by its value, it would not affect the program. Consider the following:

   $val=5;
   $alpha= function() use ($val) {return $val * $val;};

can be replaced by;

   $alpha=25;

Nothing in the program will change if either $alpha variable is used. For a simple example of referential transparency, that’s no great shakes. Besides we lose the value of changing states. However, functional programming eschews the concept of changing states. To quote one functional programmer,

Do not try to change the state; that’s impossible. Instead only try to realize the truth: There is no state.

Again, this looks nuts both conceptually and in the real world. Take, for instance, a thermometer that changes from freezing (32F / 0C) to not freezing (say 50F / 10C). The temperature has changed states! How can anyone say it has not? Or a child changes states into an adult, or a caterpillar changes states to a butterfly?

According to the functional programming model, a freezing temperature is a different object than a non-freezing one; an adult is a different object than a child, and (clearly) a butterfly is a different object than a caterpillar. So, if I say that the thermometer has changed from 32° to 33°, it is not state that has changed, it is a different object. Objects can be as granular as you like, and if you think of atoms arranged to display a ruler, you can move from one atom (object) to the next atom (object) with no state involved at all.

The State Design Pattern: Wasn’t it Immutable All Along?

The State design pattern would seem to be the polar opposite of functional programming. However, if we examine it closely, we can re-conceptualize it as object swapping. Take a simple two-state example: a light going on and off. There’s a light-on object and a light-off object. The design is the same, but we think about it in different ways. Also, the individual state methods can include nothing but lambda functions or closures. Consider Figure 1. An “on” light JPG and an “off” light JPG can be considered two separate states or two immutable objects.

Figure 1: Two States or Two Immutable Objects

Figure 1: Two States or Two Immutable Objects

To make the State pattern more “immutable-like” the interface has two constants with the URLs for the two different images. To get started, Play the light switch State application and Download the files:
PlayDownload

The application uses a simple State design pattern. All requests go through the Context, which keeps track of the current state. However, this implementation fudged a bit because each time the UI calls the Client, it creates a new Context object; so no state is saved, and I had to add a statement to use the called method to set the correct state for switching the light on and off. (Note to self: Get busy on the RESTful API!) Also, I added two constants to the interface (IState) to impose an immutable property in the state implementations. Figure 2 shows the class diagram of the implementation:

Figure 2: State design pattern implementation

Figure 2: State design pattern implementation

The pattern diagram in Figure 2 provides an overview of the classes and key methods in those classes. The LightSwitch class is just an HTML document wrapped in a PHP class, an it is where a request originates in this model. The other roles you can see in the following outline:

  • Client: Get the request from the UI (LightSwitch) and using a Context instance and method, the request is sent to the Context.
  • Context: Always the most important participant in a State design pattern, it determines the current state and passes the request to it via the appropriate method based on the request.
  • IState: The State interface specifies the required methods and may include constants.
  • Concrete States: The On / Off states (IState implementations) return the requested state-as-an-object.

With that overview in mind, you can better understand all of the singular roles of the participants. (Continue to see listings and explanations.)
Continue reading ‘PHP Functional Programming Part II: OOP & Immutable Objects’