Monthly Archive for March, 2013

Breaking Down Large PHP Problems into Classes: A Class Should Only have a Single Responsibility

UXA Little UX and HCI

I’ve been working with a student doing experiments based on Gestalt psychology and User Experience (UX) and Human Computer Interaction (HCI). She wanted to find out whether the Gestalt concepts of similarity and proximity could be applied to a user interface (UI). So she set up an experiment to see what happened.

In summary, she tested using UIs with similarity/no similarity and proximity/no proximity. The subjects were given a task that would test each condition and their times were compared. After each test, the times were saved in a MySQL database and then retrieved to compare the mean times (average amount of time) that each task took. As predicted, the raw data showed that when the Gestalt principles were observed, the task took less time than when they were not.

While just looking at the data showed a difference, she did not know whether the differences were significant. The most appropriate way to find whether the differences are significant is to conduct a statistical test called a “means test” or “t-test” that compares two means. The t-test would tell us with a precise degree of probability whether the differences were random or not. Use the following buttons to view the outcome and download the files:
PlayDownload

The T-Test

stat

Figure 1: The t-test

Figure 1 shows the statistic used for the t-test. Let’s break down the t-test:

  • t: This is the value generated by the t-test. Using it, we use a statistical look-up table to see to what degree this is significant or not. (Because the sample size is 50, the degrees of freedom is 49, and so the t value must be 3.2651 or greater for the difference to be significant at the .001 level of significance. That means there’s about 1 chance in 1000 that these differences would be random.)
  • x1, x2: The x1 and x2 values are the means. This value is easy to calculate. You just divide the total of the values in the array using the function array_sum($array) by the number of cases–count($array). (In the diagram you see the x’es with a line over them and the numbers are subscripted.)
  • Triangle: The triangle (or delta) is the symbol used for difference in the samples. The null hypothesis is that there will be no differences, and so the value of delta is zero.
  • s1,s2: The s values are standard deviations. These are the amount of differences between the observed value and the mean. In the formula, the s values are squared–s^2.The standard deviation algorithm can be found in your PHP Manual.
  • n1, n2: The n values are the total number of values in the samples. In PHP, those values can easily be determined by the count($array) function.
  • Square root symbol: We need to divide the top part of the formula by the square root of the standard deviations divided by the total number of cases in each sample. Again, that’s easy using the sqrt($calc) function built into PHP.

By breaking down the problem in this manner, you can quickly see that you need only three values and two arrays:

  1. Mean
  2. Standard Deviation
  3. Number of cases

The arrays need to be numeric, and the delta value in this case is zero; so that could be left out of the formula if we wanted. However, just to keep it in mind, it will be represented by the literal 0.

Making Simple

The purpose of this post is to illustrate the OOP principle,

A class should only have a single responsibility.

The principle is both to modularize problem solving and create reusable parts. Most PHP programmers don’t want to “waste time” creating additional code, and OOP programming that modularizes problem solving certainly requires more code than one that does not. However, the more code in a file or class, the more particularized it is and the more difficult it is to reuse. So, rather than “wasting time,” in the long run you save time by having reusable code. Keep in mind that businesses that hired coders encouraged OOP programming because over time, they spend less effort starting all over every time they wanted to change a program or write a new one. Modularized coding allowed many parts to be reused and changes could be made to even the most complex programs.
oneThing

Keeping this in mind, we can modularize the t-test into parts that not only solve the problem at hand and make it simpler to understand but is flexible enough to be reusable.

Figure 2 shows the class diagram for the t-test. As with the Chi Square example a while back, this example also uses the Template Method design pattern. However, it breaks the solution down into more parts.

Figure 2: Class diagram for means test.

Figure 2: Class diagram for means test.

The MeansTest class implements the IMeansTest interface (an abstract class) that includes a templateMethod() function to order the steps in the means test. The steps in the algorithm are cast as abstract functions to be implemented in the child class. First, it gets the means from the Mean class, then, using the mean value, it gets the standard deviation from the StandardDeviation class, and finally the MeansTest object puts them together for the t-test value.
Continue reading ‘Breaking Down Large PHP Problems into Classes: A Class Should Only have a Single Responsibility’

Learning PHP Design Pattern Author Moo Cards: 40% and 50% Discounts

mooCardA What?

The other day I was minding my own business when I got a little box in the mail from O’Reilly. It contained “Moo” cards. I’d never seen these before, but they’re really nice half-size business cards with a picture of Learning PHP Design Patterns on the front and book information on the back. Included in the information is a code on the back for a 40-50% discount. Since I won’t be running into a lot of PHP people beyond the borders of Bloomfield, CT until I go to the Boston PHP group’s conference in August, I thought it’d be a good idea to put it here. (Click the card.) If I run into you at the Northeast PHP Conference, I’d be happy to share a ‘bricks and mortar’ Moo card with you. (The above image is the actual size.)

PHP Prototype Design Pattern Part II: From Prototype to Production

appleReady for Production

Before a product goes into full production, manufacturers design a prototype to work out the bugs and improve the design. Once the prototype is ready, it is ready for production. Then all of the production copies are based on the prototype. (Of course, if you get the prototype wrong, all of your production elements will be wrong as well.)

One of the nice things about OOP is that abstract classes and interfaces act a lot like prototypes. They provide a basic design and allow the individual implementations to make variations. Think of an automobile that has certain key elements to it based on a prototype. If you have a Ford, Toyota, Volkswagen or Saab, you get a car based on a certain prototype, but you can have different characteristics based on the prototype such as color and a choice of leather or vinyl seat covers. (Even more choices are available with the Decorator pattern!) To get started, run the sample program (Outlaws and Lawmen of the Old West) and download the files:
PlayDownload

One of the more challenging aspects of the creating a Prototype pattern is the cloning, but as you saw in Part I of the Prototype discussion, in PHP, cloning is easy. So, now all we have to do is to take a quick look at the class diagram and then look at the code:

Figure 1: Prototype class diagram

Figure 1: Prototype class diagram

The Prototype Interface

This example uses an abstract class for an interface. In looking at the class diagram, all we really need is an abstract __clone() function, but adding some concrete and abstract getters and setters give us a bit more to work with. At the very base, the properties include:

  • A name (sobriquet)
  • A photo (poster)
  • Where they lived (location)

All of the functions (except one) could be abstract or all of them could be abstract, but since this is for illustration purposes, I put in some of both. I like using properties in abstract classes, and so this excludes using interfaces since they can only have abstract classes and CONSTANTS. However, if the properties ($sobriquet, $poster, and $location) were omitted, I could use an interface.

< ?php
//IWestlaw.php
abstract class IWestLaw
{
        protected $sobriquet;
        protected $poster;
        protected $location;
 
        //Outlaw or Lawman
        abstract function setPlace($where);
        abstract function getPlace();
        abstract function __clone();
 
        //Sobriquet
        public function setSobriquet($nickname)
        {
                $this->sobriquet=$nickname;
        }
 
        public function getSobriquet()
        {
                return $this->sobriquet;
        }
 
        //Wanted Poster or Lawman Pose
        public function setPoster($ePic)
        {
                $this->poster="posters/" . $ePic . ".png";
        }
 
        public function getPic()
        {
                return $this->poster;
        }     
}
?>

Once implemented, the client can then use clones of the implementations. However, we first need to implement the concrete prototype classes that will be cloned.

The Outlaw and Lawmen Prototype Implementations

This example has two implementations of the IWestlaw abstract class. The only difference between the two is that the Outlaw class has a constant that identifies the outlaw as such, and it has a property, along with appropriate getter/setter methods, that identifies the outlaw’s criminal preferences.

< ?php
//Outlaw.php
include_once('IWestLaw.php');
class Outlaw extends IWestLaw
{
        const LAWSIDE="Outlaw";
        private $crime;
 
        public function setPlace($where)
        {
                $this->location=$where;
        }
 
        public function getPlace()
        {
                return $this->location;
        }
 
        public function setCrime($doneWrong)
        {
                $this->crime=$doneWrong;
        }
 
        public function getCrime()
        {
                return $this->crime;
        }
        function __clone(){}      
 
}
?>

At the very bottom of the implementation is the __clone() implementation. Because all I’m concerned with is the capacity to clone an instance of the implementation, there’s no reason to place any content in the __clone() method. The added getter/setter for the $doneWrong (crime) property will not be part of the Lawman implementation of the IWestLaw interface (abstract class).
Continue reading ‘PHP Prototype Design Pattern Part II: From Prototype to Production’

Bound Books are Now Available!

lrg
Learning Design patterns is now available as a bound book. Click the download button to get all of the PHP files for the book FREE!
Download

The book explains the different design patterns for the downloaded examples, and if you have questions, you can address them here on this blog.

PHP Prototype Design Pattern Part I: How to Clone

cloneClone My Instance

The Prototype Design Pattern is a creational one that I’ve been warming up to lately. Basically, the purpose of the Prototype pattern is to reduce the cost of instantiating objects through the use of cloning. So, the first thing we need to do is to understand how to use cloning in PHP and what it does.

Fortunately, PHP has a __clone() function built right into it, and it makes creating a Prototype design pattern a lot easier than languages where you have to write your own clone function. So, this post will just look at how the __clone() function works and how it saves resources in programming.

Before we get going, go ahead and play the example (and meet the lovely Ada Lovelace) and download the source code:
PlayDownload
Take a look at the listings, and you’ll see where the __clone() function is located. Also, see how it is used to create a cloned instance.

A Class with a Clone Within

To clone an object in PHP, you need to create the Class you plan to clone with the __clone() function inside. So for ClassA to be cloned by $objectB, I need to include the __clone function inside ClassA. The instantiation process would look like the following:

$objectA = new ClassA();
$objectB = clone $objectA;

To get started, then, we’ll need to create a class that contains a __clone() function. This will be an abstract class, and the __clone() function will be abstract as well.

< ?php
//CloneMachine.php
abstract class CloneMachine
{
        protected $designation;
 
        public function showHelp($designate)
        {
                $this->designation=$designate;
 
                echo "";
                echo "
$this->designation

"
; } abstract function __clone(); } ?>

Continue reading ‘PHP Prototype Design Pattern Part I: How to Clone’