Archive for the 'OOP and Design Pattern Principles' Category

Page 2 of 6

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’

Share

OOP Principles: The Liskov Substitution Principle

liskovPrinciples Rule!
It’s been a while since OOP/Design Pattern principles have been a topic on this blog, and now is as good time as any. The 1987 OOPSLA keynote address by Barbara Liskov contained what has become known as the Liskov Substitution Principle. In that address and books and papers, the Liskov principle is an OOP one that is part of the more general OOP set of principles. In languages like C++ and Java where you have strongly typed languages, you can declare a variable (property) by the parent data type. Since PHP is flexibly typed, the data type can change, and while that practice [changing data types for a variable] is not recommended, it is certainly possible. As a result, it’s not as easy to explain and illustrate the principle with PHP.

Essentially, the principle holds that,

If a Client is using a reference to a base class it should be able to substitute a derived class for it without affecting the program’s operation

Actually Dr. Liskov said,:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

and I was trying to put it in less technical terms.

Why is the Liskov Substitution Principle Important?

You can easily see three reasons that the principle is important:

  1. If substitutions cannot be made then class hierarchies would be a mess. Whenever a subclass instance is passed as parameter to any method, surprises might occur.
  2. Without the possibility of Liskov type substitutions unit tests for the superclass would never succeed for the subclass.
  3. Changes are easier and more predictable because you know what to expect from the superclass.

No doubt you can find more, but for now, the Liskov substitution principle is another way to keep your code loose and reusable and subject to change.

If the Client has an object of a certain type, it should be able to substitute a derived object of the same type. For example, suppose you have an abstract class named Automobile and from that class you have subclasses of Ford, Toyota, and Peugeot. Your Client has an object, $myAuto. The $myAuto object can be any of the subclasses, and if a substitution is made for any one of them everything keeps on working without a problem and the change is unknown to the Client class. So if you substitute a Ford for a Toyota, the Client can work with the objects without having to adjust for the change. What’s more, if you want to add a Fiat or Mercedes Benz class as a subclass of Automobile, the $myAuto object handles it with nary a whimper.

The one caveat is that the subclasses must all honor the contractual conditions of the parent class. So, any methods in the parent class must be functioning in the subclass (aka, derived class.)

Now you may be thinking, So what? If you’re at all familiar with other principles of OOP and Design Patterns, this principle may sound vaguely familiar, but what is the importance of this concept/principle/idea? It is this: Because the Client is unaware of the concrete class that the object may implement, the structure is far more resilient. Not only can the same structure be reused, it can be changed, updated and generally fiddled with without easily breaking anything. (Think of adding more car manufacturers to the Automobile class.) As far as the Client is concerned, as long as the interface rules are followed with the object, everything is hunky-dory. To get started Play the example and Download the source code:
PlayDownload

A Simple Practice for PHP Programmers

As a principle, the Liskov Substitution Principle is easy to use. The problem is in demonstrating it in PHP because of the lack of assigned data types to properties. However, using PHP type hinting, you will see how it works using at a classic example where the Liskov substitution principle (LSP) is used.

Explanations of how LSP works often use a rectangle/square example. Typically most programmers see two alternatives to illustrate LSP programming a rectangle and a square; with LSP and without LSP.

Beginning with the geometric observation, all squares are also rectangles, we’re likely to create a structure like that shown in Figure 1:

Figure 1: Square is a child of Rectangle

Figure 1: Square is a child of Rectangle

After all, we can envision a square as nothing more than a rectangle with equal sides. So an operation such as,

makeRectangle(w,h);

is an effective way to make either a square or rectangle. We add the Square class simply to examine the LS Principle; otherwise creating rectangles or squares would be accomplished using the makeRectangle(w,h) method making sure that w and h are equal when making squares. The inheritance path clearly indicates that a Square object IS A Rectangle. (That is, the two have an IS A relationship.) However, because Rectangle is a concrete class if I substitute Rectangle for Square, I’m going to have to change the type. I cannot substitute an instance of Rectangle for an instance of Square. This violates the Liskov Substitution Principle.
Continue reading ‘OOP Principles: The Liskov Substitution Principle’

Share

PHP Iterator Design Pattern I: Access to Aggregates

iteratorSetting the Table

I tend to think in structural terms to address a given task. I need an object to do “X” and another object to do “Y.” This is in contrast to sequential and procedural thinking; first I’ll do this, and then I’ll do that, and then another thing. Structural thinking is easier on my brain, and it’s a lot easier to make changes and add updates. When it comes to the process of sequentially accessing the elements of an aggregate object (some kind of list), I don’t think of a sequential process, I think of an Iterator design pattern. The Iterator contains both aggregate and iterator objects. That makes it much clearer. Common PHP tasks include iterating through a MySql table. Sometimes MySql table elements are passed to PHP arrays or even XML files. Further, some lists are optimized for searching, such as linked lists and skip lists. We’ll get to those in future posts regarding the Iterator design pattern. However, in PHP, sequential storage outside of a MySql table is typically a numeric or associative array. At this point the focus is on plain vanilla lists stored in aggregate objects we call arrays. Before getting further into this topic, Play the sample and Download the code for an overview:
PlayDownload

According to the Gang of Four, the key idea in the Iterator

is to take the responsibility for access and traversal out of the list object and put it into an iterator object.

Typically, iterating through a list involves something like the following:

< ?php
class StandardIteration
{
    public function __construct()
    {
        $bigList=array('rupiah','peso', 'real', 'rupee',
                       'dollar', 'euro', 'yen', 'pound',
                       'yuan', 'dinar', 'shekel', 'krone',
                       'ringgit', 'rial', 'shilling', 'rand',
                       'ruble', 'dong');
        $counter=0;
        echo "World Currency List <br />";
        foreach ($bigList as $currency) 
        {
            echo $counter . ". " . $currency . "<br />";
            $counter++;
        }
    }
}
$worker=new StandardIteration();
?>

The “list” of elements reside in an array, and using a looping structure, programs can sequentially access all or some of the elements.

Access

Figure 1: Access through a Sequence

Figure 1: Access through a Sequence

When we think of access in PHP OOP, we typically think in terms visibility—private, protected and public. That is certainly an aspect of access, but in looking at lists, even simple one-dimensional ones residing in arrays, access is part of an order. As soon as we get to even slightly more sophisticated lists, we can see the difference in access. Beginning with Figure 1, you can see that when lists are arranged in sequences, the access is based on the position of the element in the order as shown in Figure 1. Above, in the class StandardIteration, you can see such an ordered sequence. The first currency in the list is the rupiah, and the last is the dong. They are in no order other than the one they were placed in the array. To access the Chinese yuan, for example, requires going through 8 iterations before reaching the yuan.

Figure 2: Binary tree access

Figure 2: Binary tree access

Suppose that instead of a sequence (or sequential list), we had used a binary tree as shown in Figure 2. The “7 element” is only three step 1-5-7. Binary trees are used a good deal in programming because the access paths are more efficient. Instead of going through a sequence, you program through the nodes. The quickest route to “7 element” is through the root node (1) then to the 5-node (5) and finally to the 7-element (7). So it should be no surprise that working with different types of lists is important.
Continue reading ‘PHP Iterator Design Pattern I: Access to Aggregates’

Share

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:

< !doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="easy.css"/>
<meta charset="UTF-8"/>
<title>Basics of PHP OOP</title>
</head>
<body>
<img class="fl" src="snap150.jpg" alt="snap"/>
<header>
  <h1>Basic Classes for Basic Tasks I</h1>
  Keeping objects clear and focused on a single task</header>
<div>
  <h2>Entering Data into a Table and Retrieving it</h2>
</div>
<div>Data are entered into a table through a UI, but automatically generated data also may be entered.</div>
<br />
<form action="Client.php" method="post" target="feedback">
  <div><strong>Developer Info:</strong><br />
    <label for="name">Name:</label>
    <input type="text" name="name" id="name"/>
    <br />
    <label for="email">Email:</label>
    <input type="email" name="email" id="email"/>
    <p></p>
  </div>
  <div><strong>Programming Language Used Most</strong><br />
    <input type="radio" name="lang" id="cs" value="C#"/>
    <label for="cs">C#:</label>
    <br />
    <input type="radio" name="lang" id="js" value="JavaScript"/>
    <label for="js">JavaScript:</label>
    <br />
    <input type="radio" name="lang" id="php" value="PHP"/>
    <label for="php">PHP:</label>
    <br />
    <input type="radio" name="lang" id="python" value="Python"/>
    <label for="python">Python:</label>
  </div>
  <br />
  <div>
    <input type="submit" name="insert" value="Insert Data into Table"/>
  </div>
</form>
<p></p>
<div><strong>Display All Data in Table with a new Form</strong>
  <p></p>
  <form action="Client.php" method="post" target="feedback">
    <input type="submit" name="all" value="Display all data"/>
  </form>
</div>
<br />
The PHP class uses 4 MySql fields to store and retrieve the information:
<ul>
  <li>id</li>
  <li>name</li>
  <li>email</li>
  <li>lang</li>
</ul>
<iframe name="feedback" seamless width="300" height="200">PHP</iframe>
<div>
  <p>
  <a href="EasyUpdateOOP.html">Update and Drop Files</a>
  </p>
</div>
</body>
</html>

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’

Share

The Composite Design Pattern in PHP: Part II Composing with Images

cornerDon’t forget to Program to the Interface!

While the primary principle we draw from the Composite pattern is , Favor object composition over class inheritance, as discussed in Part I of the Composite series, another important principle applies here as well. The very first principle of design patterns is, Program to an interface, not an implementation. In a sense this is saying, program to an abstract parent and not a concrete child, but if you understand an interface to be the structure implied in either an interface (as used in the first and in this example) or an abstract class, you can see what the value of that principle is.

In this part, instead of a single leaf and a hierarchy rending output, this example shows how a Composite design with multiple leaves can be used to create a mosaic—which is the essence of composite! The interface (IComponent) is little changed except the string parameter has been removed from the operation() method and replaced (for clarity) with a method named showPix() with no parameters. All of the other methods remain the same. Play the application and download the source code and files to get started:
PlayDownload

Follow the Structure; Not the Sequence

To get out of the tar pit of sequential programming, look at the structure and think in terms of using larger structural concepts. Take a look at the three key participants in the Composite pattern, beginning with the key structural participant, the IComponent interface, focusing on their structure as outlined in the interface.

<?php
//IComponent.php
interface IComponent
{
    public function showPix();
    public function add(IComponent $comOn);
    public function remove(IComponent $comGone);
    public function getChild($someInt);
}
?>

As in Part I, the IComponent has four methods to be implemented, and though all four are implemented, only the first two are used for this second part. The focus is still on the idea of composition. The fact that we don’t need the second two right now does not detract from the fact that they (remove() and getChild() methods) unimportant for the pattern; just not for this example.

So the implementation of the the Composite class looks structurally similar to that in Part I, but the constructor function has no node name to identify in a parameter. Likewise, the showPix() method is almost identical to the operation() method in Part I, and only the name of the array has changed from $aChildren to $mosaic. Also, the echo statement is no longer part of the method.

<?php
//Composite.php
class Composite implements IComponent
{
    private $mosaic;
 
    public function __construct()
    { 
        $this->mosaic=array();
    }
 
    public function add(IComponent $comOn)
    {
        array_push($this->mosaic,$comOn);
    }
 
    public function remove(IComponent $comGone)
    {
        //Code to remove component
    }
 
    public function getChild($someInt)
    {
        //Code to get child by element value
    }
 
    //Note: The following method is recursive
    public function showPix()
    {
        foreach($this->mosaic as $tile)
        {
            $tile->showPix();
        }
    }
}
?>

If you’ve played both Part I and Part II examples of Composite patterns, you know they are very different in what they generate, but the structures for both are virtually identical. Each is combining leaf elements into composite ones. Same structure; different outcomes. That virtually defines code re-use.

Parts is Parts

While the implementation of the Composite class is little unchanged, the number and implementation of the leaf nodes are different. Each leaf class has a single task and no constructor parameter. The unused methods are implemented the same. Each leaf contains an HTML tag to an image. The Composite class stores instances of leaf instances in the $mosaic array and creates rows of images that are aligned to display the tiled image. You can think of each tile in the display as a leaf, and each row a composite of tiles and the entire mosaic as a composite of the three composites that make up the rows.

<?php
class Leafr1c1 implements IComponent
{   
    /* None of this batch of methods are used by leaf participants */
    /* However in order to correctly implement the interface */
    /* you need some kind of implementation */
    public function add(IComponent $comOn){}
    public function remove(IComponent $comGone){}
    public function getChild($someInt){}
 
    /* Display tile */
    public function showPix()
    {
        echo "<img src='images/r1c1.png' alt='r1c1'>";
    }
}
?>

Each of the leaf classes is named after a column and row where the tile is to be placed. For example the leaf class to place an image in Row 2, Column 3 of the mosaic is named Leafr2c3. Likewise, the names of the PNG graphic files share the same naming conviction. So Leafr2c3 has the code to display the r2c3.png image file.

The Client

As an integral part of the Composite design pattern, the Client can be seen as the artist who composes the mosaic. He does this by selecting each tile for the rows and arranges them to get the desired picture. Because no string parameter is in the leaf constructors, each leaf added to a composition does not need a name. (In a sense, the title names have been embedded into the leaf names.) The $bigPictue property is the same name as used in the original Client example, except this time, it really will produce a “big picture.” It is the root composition made up of three row compositions that are made up of three leaf elements.

<?php
ERROR_REPORTING( E_ALL | E_STRICT );
ini_set("display_errors", 1);
function __autoload($class_name) 
{
    include $class_name . '.php';
}
class Client
{
    private $bigPicture;
 
    public function __construct()
    {
        $this->bigPicture = new Composite();
        $row1=new Composite();
        $row1->add(new Leafr1c1());
        $row1->add(new Leafr1c2());
        $row1->add(new Leafr1c3());
        $this->bigPicture->add($row1);
 
        $row2=new Composite();
        $row2->add(new Leafr2c1());
        $row2->add(new Leafr2c2());
        $row2->add(new Leafr2c3());
        $this->bigPicture->add($row2);
 
        $row3=new Composite();
        $row3->add(new Leafr3c1());
        $row3->add(new Leafr3c2());
        $row3->add(new Leafr3c3());
        $this->bigPicture->add($row3);
 
        //Create a compostion
        echo "<!doctype html><html><head>";
        echo "<link rel='stylesheet' href='india.css'>";
        echo "<meta charset='UTF-8'></head><body>";
        echo "<h1>Leaders in Composition</h1>";
        echo "<header>India</header>";
 
        $this->bigPicture->showPix();
 
        echo "<figcaption>Mahatma Gandhi</figcaption>";
        echo "</body></html>";
    }
}
$worker=new Client();
?>

In this installment, the goal is to show that the Composite design pattern is more than a tree-like hierarchy-making pattern. It is the essence of composition and the Composite design pattern. The mosaic image is a metaphor for the pattern in that it is composed of several compositions and elements within those compositions.

Adding the Final Touches

With two unimplemented methods (remove() and getChild()), in Part III of this series, you will see how they can be used for added flexibility with the Composite design pattern. I’d like to look at the original Gang of Four idea of using the Composite pattern to create a drawing program. Until next time, I welcome any and all comments.

Share