Tag Archive for 'php strategy design pattern'

PHP OOP & Algorithms II: What to Use

algorithm2What Are the Guidelines?

Like just about everything else in computing, there’s a certain amount of empirical testing. More importantly, however, are the general principles derived by both empirical and mathematical calculations. In the first post on algorithms and OOP, you saw an example that showed how many operations were necessary to find “Waldo,” a name near the end of an array of over 1,000 elements. One used a straight up loop and the other a binary search algorithm. Both were pretty quick; in fact it was hard to tell the difference in speed, and without seeing the little dots, you would not have seen the number of iterations required in each algorithm. You also saw that quadratic algorithms grew at rates that can quickly reach a point where processing comes to a crawl.

A Table Guide

Table 1 is derived from the 4th Edition of Algorithms (2011, p. 187) by Robert Sedgewick and Kevin Wayne. I’ve summarized it further. (Examples in the book are all in Java.) It is a rough but useful guide, and I have found it handy for a quick look-up.

Table 1: Algorithm Order of Growth

NameOrder of GrowthDescriptionExample
 constant 1statement   2 + 7
 logarithmic log Ndivide in half   binary search
 linear Nloop   find max
 linearithmic N log Ndivide & conquer   mergesort
quadratic N²double loop   check all pairs
cubic N³triple loop   check all triples
exponential2Nexhaustive search   check all subsets

Fortunately, most of the time our algorithms are pretty simple statements, single loops or recursive calls. All of the models in green are algorithms we should try and stick with. You should avoid the reds ones if possible.

What About Recursive Algorithms?

Those who love to profess a little knowledge like to say that recursion is slower than a loop. As indicated, we really don’t want to end up paying attention to small costs. Recursion is important, and using recursive algorithms is cost effective, especially since the difference in running time is negligible.

We often use recursive implementations of methods because they can lead to compact, elegant code that is easier to understand than a corresponding implementation that does not use recursion.
~Robert Sedgewick and Kevin Wayne

(A recursive example of a logarithmic algorithm is not included here, but you can find a recursive binary search in the post on binary searches.) What we need to pay attention to are the order-of-growth issues. For example, quadratic algorithms on the lower end of the scale are not really that bad, but when the N increases at a squaring rate, it’s easy to run into problems. So if you avoid quadratic algorithms, you’ll be better off when the N increases. On the other hand, whether you’re using a recursive method for a binary search, you’ll not see that much of a difference as the N increases compared to non-recursive methods.

A Strategy Design Pattern Handles Algorithms

This blog has lots of posts detailing the Strategy design patterns; so if you’re not familiar with a PHP implementation of the Strategy pattern, you might want to take a quick look at the code. To get started, play the example and download the code.

In the last post on algorithms, the program used a Factory Method pattern to produce an array, and in this post, the same pattern is used and two additional array products have been added. However, instead of having the algorithm classes be more or less on their own, all of the algorithm classes have been organized into a Strategy design pattern. Figure 1 is a file diagram of the objects in the application:

Figure 1: Object groupings with Strategy and Factory Method patterns

Figure 1: Object groupings with Strategy and Factory Method patterns

If Figure 1 looks a bit daunting, it is only three object groupings. The HTML and PHP Client make a request for one of seven algorithm implementations through a Strategy pattern. The concrete strategy implementations all get their data from a “data factory.” Figure 2 provides an easier (and more accurate) way to understand what’s going on.

Figure 2: Overview of the main purposes of the objects.

Figure 2: Overview of the main purposes of the objects.

So instead of having a complex task, you only have three groupings of classes and interfaces: Those making a request (Clients), those executing operations on data (Algorithms) organized as a Strategy pattern and the data itself organized with a Factory Method (Data.)

Figure 2 shows a simplified version of what the program does. The Context class considerably eases the requesting process. The HTML UI passes the name of the requested concrete strategy to the Client, and the Client uses the name as a parameter in a Context method. The Client is not bound to any of the concrete strategies because the strategy classes are handled by a Context object and method. (Click continue to see the PHP implementations of the algorithms.)
Continue reading ‘PHP OOP & Algorithms II: What to Use’


PHP Strategy Design Pattern Part II: Add a Context

pulp Adding a Context

A few years back, a post on this blog looked at examples of PHP design patterns that had missing parts. In 2006, an IBM sponsored post introduced PHPers to design patterns in “Five common PHP design patterns.” This was an important post because it demonstrated that far from being the exclusive domain of languages like Java, design patterns were applicable to PHP as well. However, of the five patterns, (Factory [Factory Method], Singleton, Chain-of-Command [Chain-of-Responsibility] , Observer, and Strategy) two (Factory and Chain-of-Command) were misnamed and misrepresented, one (Singleton) has since been more-or-less deprecated as a pattern (by no less than Erich Gamma) and the other two were iffy in their implementation.

Like lemmings following each other over a cliff, PHPers often followed each wrong example, further perpetuating the ill-formed pattern. So, when we look at patterns, lest PHP programmers be considered rank amateurs, we need to get patterns right. One of the most common mistakes with the Strategy pattern is either ignoring or leaving out the Context class altogether. In Part I of this two-part series, we saw what a Near-Strategy pattern looks like without a Context class. In Figure 1 of that same post, you can see the class diagrams of the Near-Strategy and Strategy patterns. The example in this post is of a correctly formed Strategy pattern. Play the Strategy example and Download the files with the following two buttons:

The Context Participant

To get the Context right, we need to go to the original source, Design Patterns: Elements of Reusable Object-Oriented Software. The Context participant has the following characteristics:

  • Configured with a ConcreteStrategy object
  • Maintains to reference to a Strategy object
  • May define an interface that lets Strategy access its data

At the heart of the Strategy design pattern, the Context and Strategy interact to implement the selected algorithm in the form of a concrete strategy. The key here is,

The Strategy lets the algorithm vary independly from clients that use it.

In order to do this,

A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively.

Figure 1 shows the path used in this implementation:

Figure 1: The path through the context to request an algorithm (concrete strategy)

Figure 1: The path through the context to request an algorithm (concrete strategy)

The path begins with the Client creating an instance of a specific concrete strategy (received from the HTML UI) and using that instance as a parameter to make the request through the context. From this point on, the client no longer is in contact with the strategy but instead the context. The context takes the instance passed from the client and makes the request through the strategy interface [algorithmInterface()]. Any client can make similar requests through the context by passing the concrete strategy through its context interface. That can be very handy when your program has more than a single client requiring a strategy.
Continue reading ‘PHP Strategy Design Pattern Part II: Add a Context’


PHP Near Strategy Design Pattern Part I: No Conditionals, Please

nearStratWhy ‘Near’ Strategy?

The Strategy design pattern is important because it is so useful, and two different posts on this blog have covered it in the past. What I would like to do with this implementation of the pattern is to do two things: 1) First, show how to create operations that require no conditional statements, and 2) Second, (in Part II) show the role of the Context participant. In this first part, I’d like to look at the HTML->PHP operations where specific objects (classes) can be called through HTML forms.

One of the nice things about the Strategy pattern is that the logic of it is very easy to understand; albeit on a foundational level. You have different tasks, and each task requires a different algorithm; so why not separate the algorithm operations into distinct objects (classes) and loosely bind them to the client? Each class will only do one thing, and that is to carry out an algorithmic operation. To do this, start off with a “Near Strategy”–a pseudo-patten: the Strategy design pattern missing the Context. Figure 1 shows the difference between a Near Strategy and true Strategy design pattern:

Figure 1: The Near Strategy design and the Strategy Design pattern

Figure 1: The Near Strategy design and the Strategy Design pattern

The HTML UI and the Client are not a part of the Strategy design pattern, but in this example, both are required for making requests. Before going on, try out the program by clicking the Play button and download all of the files.


You can use the files “as-is” but you will need to change the IConnectInfo.php file so that the hostname (HOST), user name (UNAME), database name (DBNAME) and password (PW) is your actual MySql database. Also, once you create a table with a name of your choosing, be careful not to create it again if you want to keep your data entered into the table!

Using Form Names for Concrete Strategy Names

One of the coolest features of PHP is the ability to use strings to create instances of classes (aka: objects). For example,

$myVar = “MyClass”;
$myObject = new $myVar();

creates an instance of the class, MyClass. Knowing this, we can create the class names in HTML as form values. For instance:

<input type=”radio” name=”callme” value=”MyClass”>
<input type=”radio” name=”callme” value=”YourClass”>

The selected radio button value can be passed in a super-global to PHP:

$myVar = $_POST[‘callme’];
$myObject = new $myVar();

Using this, the Client doe not have to work through conditional statements to decide which request to fulfill. Like the Strategy design pattern, even the Client is free from using conditional statements as can be seen in the following listing:

< ?php
function __autoload($class_name) 
    include $class_name . '.php';
Class Client
    private $chooser;
    private $instance;
    public function __construct()
        $this->instance=new $object();
$worker=new Client();

As you can see the Client class is pretty simple with no conditional statements. It takes the value of the radio button send with a Post method. The radio button group is named “sql”; so whatever button is clicked is translated into an object.
Continue reading ‘PHP Near Strategy Design Pattern Part I: No Conditionals, Please’