Monthly Archive for November, 2013

Basic PHP-MySql OOP

basicMySQLGetting the Basic with PHP-MySql

Design Patterns are general OOP solutions for any computer language, and yet each language has different typical uses. One of the most important uses of PHP is to communicate with MySql. As the “middleman” between HTML and MySql, developers need to juggle three languages well in the HTML< ->PHP< ->MySql sequence and shuffle. All of the OOP work, though, belongs to PHP since neither HTML nor MySql is object oriented. This post is dedicated to the fundamental OOP questions surrounding HTML< ->PHP connections, instantiating class instances and creating re-usable MySql classes. I’d also like to touch on using comments in code and perhaps stir up a little controversy with comments about certain “standards” for comments in PHP.

The first thing to do is to take the program for test drive and look at the code. Run the program by clicking the Play button and click the Download button to get the files.
PlayDownload

The HTML Communication

Object oriented programming is all about objects communicating with one another. The first communication is between HTML and the PHP object it first calls. As the user interface (UI), the HTML document must get data from the user and pass it to PHP for processing. In PHP object communication, each object can call the object as a whole or specify a method or property in the other object to perform a specific task. With HTML, we pretty much have to be satisfied with a call to an object (or object trigger) and depend on PHP to carry the ball from that point on. However, if an HTML document has several forms, each form can call a different object, or each form submit button can have a different name. By using the unique name for each submit button a single Client class can determine which operation the user requests. The following HTML is set up for that purpose:

?View Code HTML
< !doctype html>




Basics of PHP OOP


snap

Basic Classes for Basic Tasks I

Keeping objects clear and focused on a single task

Entering Data into a Table and Retrieving it

Data are entered into a table through a UI, but automatically generated data also may be entered.

Developer Info:

Programming Language Used Most




Display All Data in Table with a new Form


The PHP class uses 4 MySql fields to store and retrieve the information:
  • id
  • name
  • email
  • lang

You may also want to take a quick look at the CSS file that goes with the HTML.

@charset "UTF-8";
/* CSS Document */
/*66635D (gray)  E54140 (red) F7EBD5 (cream) 6CC5C1 (aqua) 000000 (black)   */
body
{
    background-color: #F7EBD5;
    font-family: sans-serif;
    color: #66635D;
}
a
{
    color: #E54140;
    text-decoration: none;
    font-weight: bold;
}
 
.warning
{
    color: #E54140;
    font-weight: bold;
}
 
h1
{
    font-family: "Arial Black", Verdana, Helvetical,sans-serif;
     background-color: #6CC5C1 ;
     color: #E54140;
     text-align: center;
}
header
{
    background-color: #E54140;
     color: #E54140;
     padding:1em;
     color: #F7EBD5;
     text-align: center;
}
 
.fl
{
    float: left;
}
 
div
{
    padding-left: 1em;
}
h2
{
    color: #000000;
}
 
li
{
    font-weight: bold;
}
iframe
{
    background-color:#6CC5C1;
}

One thing that may stir the pot (among developers) found in the HTML document is the use of iframe tags. HTML5 retained iframes, and in the jQuery Mobile documentation, you will find the use of iframes. They no longer present a hazard to SEOs; and so I don’t see the harm using them to display PHP output. Besides, I could not find a suitable replacement. (I’m not about to mix PHP and HTML to create a workable hack straight out of the 9th circle of Hell.) So see if you can live with iframes for now, and we’ll get smelling salts for the fainters.

The Client Sorts it Out

When the UI has many options that must be handled by a client object to make the appropriate request from a collection of objects, each with a single responsibility, there’s going to be some kind of conditional statement to sort out which object to use. For lots of good reasons that I won’t go into here, switch/case and if/ifelse statements are to be used sparingly and judiciously in OOP and design pattern programming. An alternative approach would be to add several methods to the Client class and then have individual trigger files launched from the different forms in the HTML document call the appropriate Client method. That’s messy, but because HTML cannot address a class method, that may actually be a more orthodox approach. (Keep those smelling salts handy.)

The basic logic of the approach used is this:

  • When a submit button is pressed it can be trapped by the isset() method
  • Provide a name for each submit button
  • Test for variable being set and not NULL
  • Once tested use unset() to remove set state
  • Call object of set variable

Now take a look at the Client class to see how that reasoning has been implemented:

< ?php
ERROR_REPORTING( E_ALL | E_STRICT );
ini_set("display_errors", 1);
function __autoload($class_name) 
{
    include $class_name . '.php';
}
class Client
{
        //Variable to select the correct class
        private $task;
 
        //Which submit button used?
        public function __construct()
        {
            if(isset($_POST['insert']))
            {
                unset($_POST['insert']);
                $this->task= new DataEntry();   
            }
            elseif(isset($_POST['all']))
            {
                unset($_POST['all']);
                $this->task= new DataDisplay();
            } 
            elseif(isset($_POST['update']))
            {
                unset($_POST['update']);
                $this->task= new DataUpdate();
            }
            elseif(isset($_POST['kill']))
            {
                unset($_POST['kill']);
                $this->task= new DeleteRecord();
            } 
        }     
}
$worker = new Client();
?>

The Client has four operations reflecting the four classes:

  1. DataEntry()
  2. DataDisplay()
  3. DataUpdate()
  4. DeleteRecord()

That’s all there is to the communication between HTML and the PHP Client class. The Client works (as do all client classes) to make requests. The origin of the request is the user through the HTML UI.
Continue reading ‘Basic PHP-MySql OOP’

Easy PHP Multiple MySql Update: Template Method to the Rescue

oopgirlThink Object Solutions

The other day I was working on an app to automatically update a site to a mobile device on a daily basis. The prototype uses a MySql table with three fields and only seven records, one for each day of the week. Each week, using an HTML UI, the administrator adds new headers, graphic urls and write-ups for each day of the week. These are stored in the MySql database, and the graphics are placed into an “images” folder.

For each day of the week, I needed to update three fields in the MySql table. In looking at the MySql docs I found that updates are carried out one field at a time even though I found some workarounds, none seemed too reliable, and the docs suggested as much. So I’d have to make three separate operations. That should be easy enough—a single update class with methods for each of the three fields I needed to update. Before we get started, you can see the update process and download the code using the two buttons below:
PlayDownload

One Class to Handle Multiple Updates

What makes SQL updates easy is that the SQL statements usually only involve a single field and table. So one way to look at multiple updates is to take three simple statements and provide each one its own method. There is a sequence to follow; so why not put them into a Template Method? (See previous posts on the Template Method design pattern in PHP for more details on its purpose. An overview can be found in the Design Pattern Table).

To start off, we’ll see what the skeleton of the operations look like:

  1. update header
  2. update picture url
  3. update write-up

Next, we’ll create an abstract class to reflect that order but not providing any content. Also, we’ll add properties likely to be needed:

< ?php
abstract class IUpdate
{
    //Update methods
    abstract protected function doHeader();
    abstract protected function doPix();
    abstract protected function doWriteup();
 
    //Update Properties
    protected $pixhead;
    protected $pix;
    protected $writeup;
    protected $day;
 
    //MySql Properties
    protected $tableMaster;
    protected $sql;
    protected $hookup;
 
    //Template method
    protected function updateAll()
    {
        $this->doHeader();
        $this->doPix();
        $this->doWriteup();
    }
}
?>

With the template method in place (updateAll()), build a class to implement the abstract methods. The data for the methods is contained in the HTML variables passed from the UI; and we’ll need a day-day-of-the week object to plant the date in the correct location. First, look at the Update class and then the HTML UI that passed on the data:(Click the link to see the rest of the post and how the template method is implemented.) Continue reading ‘Easy PHP Multiple MySql Update: Template Method to the Rescue’

PHP Builder Design Pattern Part II: Iterating through an Interface

practicalBuilder250Getting the Director Right

Part I of the Builder two-part series explains the Builder pattern and provides a simple example. Back in early 2009, I had used a similar example in ActionScript 2.0 that performed a similar task; namely building different Web pages from a single Builder pattern. (If you experienced déjà vu, it may be that you came across that earlier post.) At the time I added all of the necessary participants, but I really was not too concerned with certain details because the goal focused more on getting the participants to perform their tasks correctly than on some of the details. In Part I, the PHP example paid closer attention to details, but again, the focus was on exposition more than detailed features.

Figure 1: Director details in Builder class diagram.

Figure 1: Director details in Builder class diagram.

Figure 1 shows that portion of the original Gang of Four class diagram illustrating the role of the Director. Significantly is the pseudocode notation indicating some kind of loop through an object fires off the concrete Builder parts. In Part I, the Director simply runs all of the methods attached to a concrete builder. Most of the examples that I found of the Director, ranging from PHP to Java, use the same general approach.

Upon closer examination of the examples shown in the original Design Patterns: Elements of Reusable Object-Oriented Software, I realized that two different examples illustrated the Builder. The first one is an RTF Reader and the second is based on a Maze example from an earlier chapter. I had been digging through the code in the maze example without much luck. In the pseudocode notation of the RTF Reader, however, it shows a while loop used in conjunction with a switch statement. I tried writing similar code in PHP, and it worked like a champ, but it was not very reusable. (I rarely imply that GoF might have done something less than perfect!) So I went to work using the more abstract pseudocode notation in the structural class diagram. However, before getting into that, go ahead and test the application with the Play buttons and download all of the code.
PlayAPlayBDownload

Iterating Through an Object in PHP

All I needed to do was to create a simple loop that would iterate through an object. Originally, I thought that I’d need to use an object created by implementing a concrete Builder. However, in looking closely at the Builder class diagram, you can see that the Builder interface does not include a getResult() method. That method is only in the concrete Builder to get the assembled Product. Also, I found that I got a constructor function (__construct()) if I used a concrete Builder as a target object. So why not use the interface as the object? Figure 2 shows the general method for finding the methods in a class, and it works for interfaces as well.

Figure 2: Getting methods from classes and interfaces

Figure 2: Getting methods from classes and interfaces

So far so good. Now I have an object with all of the method names in string format. As you may know, PHP allows you to use strings to create variables, but you can also dynamically generate usable methods using variable functions. Figure 3 shows the format with an example of how to do it with a string stored in a PHP variable.

Figure 3: Using a string value to call a class method

Figure 3: Using a string value to call a class method

The trickiest part for me was remembering to place a ‘$’ in front of the method. However, once I got used to that idea, the rest was a matter of iterating through the object containing the methods and placing them on a concrete Builder instance. As you can see in the following listing the Director class is now much more re-usable:

< ?php
//Director.php
class Director
{
    private $builder;
    private $builder_methods;
    public function doBuild(IBuilder $buildNow)
    {
        $this->builder=$buildNow;
        $this->builder_methods=get_class_methods('IBuilder');
        foreach($this->builder_methods as $part)
        {
              $this->builder->$part();
        }
    }
}
?>

Given this format, you can use the identical Director for any PHP Builder application you might create. The only change would be the name of the interface from IBuilder to whatever name you want to use. It pulls out all of the abstract method names from the interface and then assigns then to whatever concrete Builder instance is passed to it. It does not matter how they’re implemented as long as they adhere to the structure. However, you may also create different Directors using the same Builder interface by ordering the building blocks in a different way. (More on this later.)
Continue reading ‘PHP Builder Design Pattern Part II: Iterating through an Interface’