Archive for the 'Introduction to Design Patterns' Category

PHP Class Origins: An OOP Job for the HTML UI

couchPotatoPutting HTML to Work

At some point in OOP development with PHP, I quit putting little PHP code snippets in HTML. I either left all PHP out of HTML or encapsulated HTML in a PHP heredoc string inside a class. In that way, all PHP would be part of an OOP order without any loose ends. That may seem overly fussy, but it avoids the slippery slope of degenerating back into sequential programming——patchwork quilt programming.

However, such a practice should not disallow HTML from helping out in an OOP project. A lot of times, I found myself sifting through class and method options using more conditional statements than I wanted in the Client. I realized that I could just pass the class name directly to the Client from a superglobal with origins in an HTML input form. Likewise, I could do the same for methods, and this has become a useful standard operating procedure.

To better illustrate using the HTML UI in launching a selected class object, the following application uses the color and number input elements with both class and method information stored in HTML element values. Both are trivial, but help illustrate the point: (Use Firefox, Chrome or Opera–neither Safari nor Internet Explorer implemented the HTML5 standard color input element.)
PlayDownload

It’s odd in a way that PHP developers (myself included) are so used to using HTML UIs for data input into MySql databases or making other choices, but few use the UI for calling classes and methods. However, it’s both easy and practical.

Where to Put the OOP in HTML?

You can place class and method names as values anywhere in form inputs that you’d put any data passed to PHP as superglobals. One input form I found useful is the hidden one. It’s out of the way, and you can build forms around the class with other superglobal inputs as methods. Using radio button inputs is another nice option because you can use them either for calling classes or methods with the mutual exclusivity assurance of knowing that not more than one will be called from a given group. To get started, take a look at the HTML:

?View Code HTML
< !DOCTYPE html>


    
    Unsetting Superglobals with Classes and Methods

 

    

Classes and Methods

Choose color from the color window:

Divide or modulo the following two numbers:
First:    Second:   
 Divide the second by the first
 Modulo the second by the first

The code has two forms, alpha and beta, and you can think of them as I/O for two different classes. The feedback is returned to the iframe named feedback. Both forms have the action calls to Client.php. So the general plan is:

Client → Class->method()

In the alpha form, the class is ColorClass and the method is doColor()—both in hidden input elements. The name for the class element is “class” and the name for the method element is “method.” All the user does is to choose a color that is passed through the superglobal associated with the color input element.

In the beta form, the class is MathClass placed in a hidden input element. The user chooses either a division or modulo operation from the two radio input elements where the names of the appropriate methods are stored. Once again, the name for the class element is “class” and with mutually exclusive choices the radio button elements for selecting the method, the name is “method.” In this way, whatever superglobal named “class” will fire the correct class and call the correct method with the superglobal named “method.”

The Client

As usual, the Client is the launching pad for the operations. If your application uses different client classes depending on user choices, it’s an easy matter to have unique client names for different forms. In this particular case, the Client class doesn’t care about the form of origin for the request. It just takes the class superglobal and method superglobal names and generates a call to the appropriate class and method.

As an aside, the Client in OOP should not be as rare as some perceive it to be. In one way or another, users (or non-human request mechanisms) employ some way to request that the software do something. The Client, as a participant in a structure, is in virtually every design pattern in one way or another. Even when the Client is not directly or implicitly in a design pattern, The Gang of Four reference it as related to one of the participants in the pattern. So while this example does not use a design pattern, the Client works perfectly well in any OOP program.

< ?php
/*
 * Set up error reporting and
 * class auto-loading
*/
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');
 
//Class definition
class Client
{
    private static $object, $method;
    //client request
    public static function request()
    {  
        self::doSuper();
        $operation = new self::$object();
        echo $operation->{self::$method}();
    }
 
    private static function doSuper()
    {
        self::$object = $_POST['class'];
        self::$method=$_POST['method'];
        unset($_POST['class']);
        unset($_POST['method']);
    }
}
Client::request();
?>

The Client file first takes care of error reporting and automatically calling classes. One experienced developer told me that adding an error-reporting function was unnecessary because it could be automatically turned on in the php.ini file. That’s true, but since I work with many different PHP environments where I have no control over the php.ini file, I’ve found it to be a good practice. You only have to put it in once place, and it takes care of error reporting for the entire program. Besides, I found that one safeguard against easy hacking is to turn off error reporting so that hackers cannot see the names of the classes involved in the application. For this blog, though, I leave the error reporting on because there’s nothing on this blog I want to hide. (Change the init_set from “1” to “0” to turn off all error-reporting.)

No Returns from Constructor Functions

The first incarnation of this application used the same two forms, but the alpha form only had the class name with the results planned to be sent back for output using a return statement. I kept getting errors, and then I learned that constructor functions (those using the __construct() method) have no returns. All they do is to instantiate the class. If you do not use the __construct() method, there’s an invisible automatic constructor function that does that for your as soon as you call new ClassName().
Continue reading ‘PHP Class Origins: An OOP Job for the HTML UI’

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 OOP & Algorithms I: An Introduction

quadAvoiding the Misinformed

Programmers often spend more time un-doing bad information than using good information. One of the comments that set me off recently was someone “explaining” to others on a blog why PHP was not an object oriented language. Then he continued to blather on about the difference between compiled and interpreted languages. Whether or not a language is compiled or not has nothing to do with whether or not it is an object oriented language. Having interfaces, classes and communication between objects are the key criteria of an OOP language, and certainly since PHP5 has been a full-fledged OOP language. (We PHPers should not feel singled out because I recently saw post where a Java programmer pronounced that neither Python nor Perl were OOP, and she was “informed” otherwise by irate Python programmers. Perl has been OOP since V5.) So here I am again wasting time grumbling about people who don’t know what they’re talking about.

Instead of frothing at the mouth over the misinformed, I decided to spent more time with the well-informed. To renew my acquaintance with algorithms I began reading Algorithms 4th Ed. (2011) by Sedgewick and Wayne. Quickly, I learned some very basic truths about algorithms that had been only vaguely floating around in my head. First and foremost are the following:

Bad programmers worry about the code.
Good programmers worry about data structures and their relationships.
Linus Torvalds (Creator of Linux)

Since we’ve been spending time on this blog acting like good programmers, that was reassuring. In this post, I’d like to look at two things that are important for developing algorithms: 1) What to count as a “cost” in developing algorithms, and 2) Identifying good and bad algorithmic models. First, though, play and download the example. Using two different algorithms, a logarithmic and a linear (both pretty good ones), I’ve added “dots” to loop iterations to visually demonstrate the difference between a logarithmic algorithm (binary search) and a linear algorithm (loop). The “expense” of the algorithm can be seen in the number of dots generated.
PlayDownload

The example is a pretty simple one. However, since this blog is about PHP Design Patterns, I added a little Factory Method. The two algorithm classes act like clients making requests through the factory for a big string array with over 1,000 first names. Figure 1 shows the file diagram:

Figure 1: File diagram for use of Factory Method by two algorithm clients.

Figure 1: File diagram for use of Factory Method by two algorithm clients.

In looking at the file diagram, you may be thinking, “Why didn’t you use a Strategy pattern coupled with that Factory Method?” I thought about it, but then decided you could do it yourself. (Why should I have all the fun?)

Lesson 1: Leave the Bag of Pennies

The first lesson I learned in Bank Robbery 101 was to leave the bag of pennies. They’re just not worth it. Speed is everything in a bank robbery, and so you pay attention to how to get the most with the least time. The same thing applies to analyzing algorithms. For example, an object (as compared to an integer, boolean or string) has an overhead of 16 bytes. I have actually seen posts intoning, “objects are expensive…” Just to be clear,

Objects are not expensive. Iterations are expensive, quadratic algorithms are expensive.

In evaluating an algorithm you need to see how many operations must be completed or the size and nature of the N. An N made of up strings is different than an N made up of Booleans or integers. A quadratic (N²) and cubic (N³) algorithm are among the worst. They’re gobbling up kilo- or megabytes, and so that 16 bytes seems pretty silly to worry about. So instead of seeing an algorithm weight expressed as N² + 84 bytes, you’ll just see it expressed as ~N². (When you see a ~ (tilde) in an algorithm, it denotes ‘approximately.’) Another way of understanding the ~ is to note, They left the bag of pennies.

Lesson 2: Watch out for Nested Loops; they’re Quadratic!

I’ve never liked nested loops, and while I admit that I’ve used them before, I just didn’t like them. They were hard to unwind and refactor, and they always seemed to put a hiccup in the run-time. Now I know why I don’t like them; they’re quadratic.

Quadratic algorithms have the following feature: When the N doubles, the running time increases fourfold.

An easy way to understand the problem with quadradics is to consider a simple matrix or table. Suppose you start with a table of 5 rows and 5 columns. You would create 5² cells—25 cells. Now if you double the number to 10, 10² cells = 100. That’s 4 x 25. Double that 10 to 20 and your have 20² or 400. A nested loop has that same quality as your N increases. If both your inner and outer loop N increases, you’re heading for a massive slowdown.

Algorithms, OOP and Design Patterns are Mutually Exclusive

An important fact to remember is that good algorithms do not guarantee good OOP. Likewise, good OOP does not mean good algorithms. Good algorithms make your code execute more efficiently and effectively. Good OOP makes your programs easier to reuse, update, share and change. Using them together is the ultimate goal of a great program.

PHP OOP: Back to Basics

beginBack to Basics

Whenever I venture outside of PHP, which has become more regular as I’m working on app development in both iOS and Android. The former is Objective C and the latter, Java. Both languages are embedded in OOP and design patterns. It is during these ventures abroad (so to speak) that I’m reminded of some core issues in good OOP. I usually notice them when I realize that I’m not exactly paying attention to them myself.

Don’t Have the Constructor Function Do Any Real Work

When I first came across the admonition not to have the constructor function do any real work, I was reading Miško Hevery’s article on a testability flaw due to having the constructor doing real work. More recently, I was reviewing some materials in the second edition of Head First Java, where the user is encouraged to,

Quick! Get out of main!

For some Java and lots of C programmers “main” is the name for a constructor function, but I like PHP’s __construct() function as the preferred name since it is pretty self-describing. “Main” is a terrible name because the real main is in the program made up of interacting classes.

In both cases, the warning about minimizing the work of the constructor function is to focus on true object oriented applications where you need objects talking to one another. Think of this as a series of requests where a group of people are all cooperatively working together, each from a separate (encapsulated) cubicle, to accomplish a task. By having the constructor function do very little, you’re forcing yourself (as a programmer) to use collaborative classes. Play the example and download the code to get started:
PlayDownload

A General Model for PHP OOP

As a nice simple starting place for PHP OOP, I’ve borrowed from the ASP.NET/C# relationship. ASP.NET provides the forms and UI, and C# is the engine. As an OOP jump-off point, we can substitute HTML for ASP.NET and PHP for C#. The Client class is the “requester” class. The UI (HTML) sends a request to the Client, and the Client farms out the request to the appropriate class. Figure 2 shows this simple relationship.

Figure 1: A Simple OOP PHP Model

Figure 1: A Simple OOP PHP Model

If you stop and think about it, OOP is simply a way to divide up a request into different specializations.

Avoid Conditional Statements if Possible

Figure 2: Requests begins with a UI built in HTML

Figure 2: Requests begins with a UI built in HTML

If you avoid conditional statements, and this includes switch statements, I think you can become a lot better programmer. In the example I built for this post, the user chooses from two different types of requests (classes), and each request has a refined request (method) that provides either of two different kinds of math calculations or display options. Figure 2 shows the UI (HTML) for the example. If the user selects “Do a Calculation” it sends the request to the Calculate class, but if the user selects “Display a story”, the request is handled by the Display class. Further, not only must the right class be selected, the right method in that class must be selected as well. The obvious answer is to get information from the UI and using a switch or set of conditional statements work out in the Client how to handle each request. You could even use (shudder) nested conditional statements. That approach could work, but when you start piling up conditional statements, you’re more likely to introduce errors, and when you make changes, you’re even more likely to make errors. The only good thing about conditionals is that you don’t have to tax your brain to use them.

Suppose for a second that all of your conditional statements were taken away. How, using the information sent from the HTML UI to the Client class can the selections be made without conditional statements? (Think about this for a moment.)

Think, pensez, pense, думайте, piense, 생각하십시오, denken Sie, 考えなさい, pensi, 认为, σκεφτείτε, , denk

Like all things that seem complex, the solution is pretty simple. (Aren’t they all once you know the answer.) Both classes were given the value of their class name in their respective radio button input tags. Likewise, the methods were given the value of their method names. With two radio button sets (request and method), only two values would be passed to the Client class. So all the Client had to do was to use the request string as a class name to instantiate an instance of the class, and employ the following built-in function:

call_user_func(array(object, method));

That generates a request like the following:

$myObject->myMethod;

In other words, it acts just like any other request for a class method. By coordinating the Client with the HTML UI, that was possible without using a single conditional statement. In this next section, we’ll now look at the code.
Continue reading ‘PHP OOP: Back to Basics’