Is PHP an OOP Gateway Drug?

gatewayIs OOP in PHP going to Help in Other Languages?

PHP is a great tool for working with both Web-based languages like HTML5, JavaScript, CSS3 and jQuery (actually a kind of JavaScript). Of course it’s an essential tool for working with SQL and the kinds of server-side operations that can only be done with a server-side language like PHP.

With the advent of mobile devices, PHP developers are able to add to help recognize devices through user-agents, but sniffers are plagued by both the vague information provided by the user-agents and may not be able to tell the difference between different screen widths and resolutions with the same user-agent information; like iPads and iPad Minis. Microsoft has the same user-agent id for all of their devices–“trident.”

Web Apps and Device Apps

PHP has been a great tool in Web app (applications that run in a browser) development for mobile devices, but these apps are largely dependent on an Internet connection, and unless there’s some way to add a local host to an Android-based Note or iOS-based iPhone, you rely on a connection to the Web. Even with WiFi being widely and generally available, an app that runs on the native Android OS or the Apple iOS (Device App) has lots of advantages over a Web app.

Don’t get me wrong. Web apps have tons of advantages over device apps when it comes to development and distribution. All devices that have browsers can run Web apps, but apps made for an Android will not run on iOS devices and vice versa.

So if you know PHP (and lots of other Internet languages), at some point you may have to bite the bullet and download the (free) Android and/or iOS SDK (Software Development Kit). The good news is that if you’ve been working with PHP OOP and design patterns, much of the code environment will look very familiar. The IDEs used by both the Android and iOS SDKs are very similar. The development process, though, takes place within classes and structures that you will be familiar with—depending on how much you’ve been experimenting with PHP OOP and design patterns.

For example, the following is a simple Swift class that generates a message—not too dissimilar from what JavaScript does with an alert() function.

import UIKit
 
class ViewController: UIViewController
{ 
    @IBAction func showAlert()
    {
        let alert = UIAlertController(title: "Sandlight Productions, LLC",
            message: "Messages for the World!",
            preferredStyle: .Alert)
 
        let action = UIAlertAction(title: "Sandlight", style: .Default, handler: nil)
 
        alert.addAction(action)
 
        presentViewController(alert, animated: true, completion: nil)
    }
 
}

Both the Android and iOS SDKs have lots of importable classes, and the imported UIKit has objects for the UI. The class declaration,

class ViewController: UIViewController

would be like declaring

class ViewController implements UIViewController

in PHP. So, while some different operators are used (e.g., : instead of implements) most of the statements are pretty close to those in PHP.

Some, though, are special to both the framework and the language. For instance,

@IBAction func showAlert()

does not have an equivalent in PHP for the whole method. The @IBAction connects the source code to a UI object. The showAlert() method, in this example, is connected to a button in the Interface Builder, part of the iOS SDK. Further, func is used instead of function used in PHP.

In declaring variables, Swift, uses the let keyword and the = assignment operator, and Swift does not use the new keyword in creating objects. For example, in Swift,

let alert = UIAlertController(//parameter list);

would be,

$alert = new UIAlertController(//parameter list);

in PHP. If you understand something about OOP and design patterns, this other type of programming makes more sense than if you do not.

Figure 1 shows the output on a simulator developed in the iOS SDK:

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

Figure 1: Landscape view of the alert in an iPhone 5s simulator.

In and of itself, it’s no great shakes. However, it can be run anywhere and without a browser or an Internet connection. What’s important is that those working with OOP and design patterns in PHP are far closer to the languages used for Android (Java) and iOS (Swift). So if you start getting clients who demand to have their own apps to be downloaded to their phones and used without a browser, don’t be afraid to start making some simple ones. You can even create a device app that calls up a mobile app written in PHP and jQuery Mobile. The big advantage of that is you can access an SQL database.

Event Driven Programs and Programming: Not So Much PHP

If you’ve ever made a game—especially the arcade type—you’re probably familiar with “event-driven programming.” Languages like ActionScript, including OOP and design pattern designs, used to be used a lot in event-driven software development. The State design pattern is often used for event-driven programs since the states keep changing with new information from the user. The events are typically made up by the user tapping, sliding and dragging objects on the screen. PHP at some base is more of a data-getting and setting type of software. The getting and setting is done in conjunction with MySQL and the SQL language.

A lot of mobile app development is done with event-driven processes, and at least in the SDKs for iOS and Android, the frameworks are set up in classes and more state-like programming than you’ll see in most PHP. However, on this blog, the Client-Request model is easily applicable to event-driven kinds of applications. A number of PHP programmers have some interesting suggestions for event-driven programming and programs, but I’m not sure how well they’d work compared to languages like Python where the connections to the event-producing object (e.g., mouse/finger clicks/taps and keyboard entries) are more direct. PHP is a bit too dependent on HTML and JavaScript to handle events in client-side events.

In any event, using OOP and design patterns in PHP is very transferrable to other languages. The same is true in using the logic and structure of functional programming. So, if you’re thinking about jumping into either iOS or Android app development, you’ve be entering a familiar programming environment if you understand working with OOP and design patterns in PHP. Don’t be afraid of event-driven programs even though they’re not exactly common in PHP. The structures you will work in will be very familiar.

Share

PHP Command Design Pattern: Part I

commandEncapsulate a Request

On occasion when developing an application, you may want to issue a request, but you may not know about the requested operation or its receiver. Imagine that you’re developing a game, and you’re working on a “Commander” (like Captain Kirk of Star Trek). The commander will issue commands, but during development or execution, you’re not sure who’s going to carry out the command or exactly how it’s going to be done. For instance, suppose that a Weapons Officer on the bridge simply pushes a button when the Captain issues a command to fire a photon torpedo. However, suppose that the bridge is damaged and the Weapons Officer wounded and cannot carry out the command. Any decent game designer would allow for someone else to launch the torpedoes; a crew member working in the torpedo bay, for example. Therefore, you would not want to tightly couple the action of firing a photon torpedo with the Weapons Officer. Something like;

weapons_officer->firePhotons()

would not be a good idea. Instead, you’d want the request to be handled by anyone who could get to the torpedoes triggering mechanism—no matter who it was or what triggering device was employed.

The Command design pattern encapsulates the request as an object, and allows you to add parameters to the clients with different requests. You can also support undoable operations—like firing off a photon torpedo! In this particular example, the participants and implementation is quite simple. I employed a helper class (Move) to add a little flair to the example, but otherwise, it’s a very simple implementation of the Command design pattern. Fire off the torpedo and download the files to get started:
torpedoDownload

The movement operations were taken from an earlier post on this blog of working with SVG files—once again illustrating the re-use functionality of OOP design. The helper class, Move is almost wholly a re-use of the earlier implementation. The sound was added to the class for this example.

The Wholly Involved Client

The requesting client is fully involved in the Command pattern. It is associated directly with both the Receiver and the ConcreteCommand classes. Figure 1 shows the pattern’s class diagram:

Figure 1: Command class diagram

Figure 1: Command class diagram

In this example, I employed a single Client, Receiver, Invoker and ConcreteCommand. Largely, I re-purposed an abstract example that Chandima Cumaranatunge had used in ActionScript 3.0 Design Patterns that we had co-authored in 2007—the main difference being that the example is written in PHP and I added an action that involved sound and animation. However, it is largely the same. In looking at the code in the Client, you can see that it creates instances of a ConcreteCommand, Receiver and Invoker.

<?php
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');
 
/* Client */
class Client
{
    public static function request()
    {
        $rec = new Receiver();
        $concom = new ConcreteCommand($rec);
        $invoker = new Invoker();
        $invoker->setCommand($concom);
        $concom->execute();
    }
}
$worker=Client::request();
?>

As you can see, the Client, chooses the concrete command and the invoker. Figure 2 shows the file diagram for this Command implementation:

Figure 2: Command file diagram

Figure 2: Command file diagram

This pattern can have different commands and different invokers, but the key lies in the Command interface (ICommand) that includes an execute() method that invokes the command. It doesn’t concern itself with what other object does the invocation; it just provides the interface for some object to carry out the command.Using the bare minimum, the interface has a single abstract method:

<?php
interface ICommand
{
   function execute( );
}
?>

The design allows for a number of different ConcreteCommand classes, especially flexible because of the simplicity of the interface. However, in this example, only a single concrete command implements the interface.

<?php
class ConcreteCommand implements ICommand
{
    private $receiver;
    function __construct(Receiver $rec)
    {
        $this->receiver = $rec;
    }
    public function execute()
    {
        $this->receiver->action();
    }
}
?>

The receiver has been identified by the Client and passed to the parameterized ConcreteCommand by the Client. The Client acts very much like a conductor in this pattern. It pulls a the pieces together and determines how they will interact together. All of the work is to carry out the command realized in the Receiver class.

The Invoker Makes it Happen

Returning to the Star Trek example where the Captain commands the Weapons Officer to “fire a photon torpedo,” the Weapons Officer is the invoker. That is, by pressing the Fire button, she executes the command. However, as we noted, maybe the Weapons Officer is unable to carry out the order because she has been knocked out in a battle, and so someone else has to do it. Because the command and the invocation of the command are loosely coupled, any available invoker could carry out the command. First, take a look at the Invoker class:

<?php
class Invoker
{
    private $currentCommand;
    public function setCommand(ICommand $c)
    {
        $this->currentCommand = $c;
    }
    public function executeCommand()
    {
        $this->currentCommand->execute();
    }
}
?>

Note that both a method for setting the command and one for executing the command are part of the Invoker class. The Client sets the command, but how is it executed? Again, it is the Client, but the execute() method is through the ConcreteCommand instance; also called by the Client.

The Receiver Knows What to Do

In order for the command to be carried out, at least one object needs to do what the command requires. In this case, it’s the Receiver. Following the path so far:

  1. The Command tells what to do.
  2. The Invoker tells an object to carry out the command
  3. The Receiver carries out the requirements of the command.

Keep in mind that all of this is done with loosely coupled objects, and different participants can carry out the different roles.

<?php
class Receiver
{
   private $speed;
   private $photon;
 
   public function action()
   {
         $this->speed= 20;
         $this->photon = 16; 
         $launcher=new Move();
         echo $launcher->setVelocity($this->speed,$this->photon);
   }
}
?>

I suppose this is a bit elaborate for an abstract example, but it seemed a little more illustrative with something other than an echo statement that the Receiver object announced. Besides, it illustrates re-use of a class as a helper class for the Receiver to do a bit more. As you can see from Move helper class, a the property IDs from the original use have been retained—e.g., ‘ship’ and ‘torpedo’ used for the same purpose.

<?php
//Helper class
class Move
{
   private $velocity;
   private $capacity;
 
   public function setVelocity($speed,$ship)
   {
      $this->velocity=$speed;
      $this->capacity=$ship;
 
      $ship =<<<SHIP
      <!DOCTYPE HTML>
      <html>
         <head>
         <script type="text/ecmascript">
           // Single global variable
           var photon = 0; // Photon torpedo x position.
 
           function drawSVG()
           {
             //Interval Timer loop
             moveLoop = setInterval(fireTorpedo, $this->capacity);
           }
 
           function fireTorpedo()
           {
             // Change the photon torpedo's position
             photon += $this->velocity;
             photon = photon % 500;
             phpton.setAttribute("x", photon);
           }
         </script>
         </head>
           <body onload="drawSVG()">
             <!-- Create the SVG galaxy. -->
             <!--<?xml version="1.0" standalone="no"?> -->
             <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
               <svg width="500" height="200" viewBox="0 0 500 200"
                  xmlns="http://www.w3.org/2000/svg" version="1.1">
                 <desc>Oopz</desc>
 
                 <!-- Show outline of 2D Galaxy using 'rect' element -->
                 <rect x="0" y="0" width="500" height="200"
                     fill="navy" stroke="blue" stroke-width="1"/>
                 <!-- Space craft Oopz -->
                 <rect x="100" y="100" width="30" height="20"
                     fill="yellow" stroke="#369" stroke-width=".4" id="phpton" />
               </svg>
               <audio autoplay>
                  <source src="photon.ogg" type="audio/ogg">
                  <source src="photon.mp3" type="audio/mpeg">
               </audio>
       </body>
       </html>
SHIP;
      return $ship;
   }
}

You can revise the actions of the Receiver to virtually anything you want. The important point with the Command class is that the original command (request) is encapsulated through the ICommand interface, and in the development process there can be any number of different requests fulfilled by different receivers and launched by different Invoker objects. Further with added commands, you can also add new invokers and ever receivers.

Beyond Abstract Command Structures

Even though this example has not been quite as abstract as originally planned, it is still pretty basic. What I’d like to do in subsequent examples is to build on this basic pattern where multiple commands, invokers and receivers work in concert through the Command design pattern. In the meantime, feel free to try out some of your own ideas and offer suggestions for further improvement and/or refinement.

Share

PHP Interpreter Design Pattern

interpreterInterpreting Postfix

Even though we may not realize it, one of the most common computer languages we use is Adobe’s PostScript. PostScript printers contain a language called PostScript, a postfix language based on a stack analogy. (Postfix also is called reverse Polish notation after the Polish mathematician Jan Łukasiewicz who developed the mathematical notation placing of the operator after the operands.)

Stack operations are compared to a cafeteria stack of trays. The last tray added to the stack is the first one to pop off. Imagine each tray with a value and each third tray with a mathematical operator. The bottom most tray is to the far left and the top tray is to the far right. With three trays, reading from left to right, we might find the first and second trays to be operands (numbers) and the third one to far right (top) an operator. So if the first operand is 5 and the second operand is 4 and the operator is add or (+), the three trays would be removed and replaced by a single tray with a value of 9—the sum of 5 and 4.

The following shows an example of this notation:

30 2 *
Result: 60

In order to correctly interpret a postfix expression as an infix one (the kind we’re used to using in PHP, like $total = 5 + 4;), this post uses an Interpreter design pattern that interprets a postfix expression so that PHP understands what to do with it as a math operation. The implementation of the Interpreter pattern is very simple and may lack some of the more subtle aspects of the pattern. However, it is one implementation that uses all of the pattern’s participants and should be easy to understand.

Using a simplified version of the Interpreter design pattern, you can practice math operations using a postfix calculator that interprets PostScript operations as PHP math operations. If the operation reminds you of certain of your calculator’s behavior, it’s probably because a lot of calculators use postfix to solve problems.

A further simplification is that this “calculator” only returns the results of a single two-operand calculation. A more common postfix expression may have several operators such as the following:

1 5 + 2 * 6 / result=2
1 and 5 add = 6
6 and 2 multiply = 12
12 and 6 divide = 2

This interpreter could be modified to take more complex expressions, but to get started, this one is simple by design. Click the play button to see how the program works and download the source code:
PlayDownload
Try some different entries using postfix notations with the caveat that all operators are spelled out—add instead of + and mod instead of %.

Interpreting Differences

The Interpreter design pattern as described by Gamma, et al can be used to express instances of a recurring problem as sentences. Interpreting the sentences then solves the problem. Right off the bat I was thinking, ¿Como está usted? translates to How’s it going?, but that’s not exactly what GoF had in mind. Any spoken language is a bit too big for this kind of interpreter. Instead, the pattern describes how to define a grammar for simple languages. Gamma and his associates use the example of regular expressions, so loved by Perl programmers.

So when I went looking at some Interpreter examples, besides regular expressions, I found converters from Roman numerals to regular numbers, a Boolean language, a musical note interpreter from do, rey, me, fa, so, la, ti to Hertz (Hz) values, calculations using postfix notations and some other fairly modest examples. Because of my experiences with postfix languages, I decided to do one that set up as a PostScript data entry that would resolve to an outcome (solution) to the results of a postfix statement. I decided on PostScript whose math operators are word-like and not symbols. (e.g., Instead of using / for division, it uses div.) Besides, most laser ink-jet printers are PostScript. This would be a little more than the usual minimalist example since the user can use it to practice and learn PostScript math entries.

Interpreter Design Pattern Formal Features

Figure 1 provides an overview of the Interpreter pattern. Note that the Client is part of the pattern (instead of implied or not at all). Also note that the Client holds references to both the Context class and AbstractExpression interface.

Figure 1: Interpreter Class Diagram

Figure 1: Interpreter Class Diagram


Of all of the design patterns I’ve seen, this one has the most loose ends. Any statement put into a string and then interpreted generally requires some kind of parsing. GoF note the need for parsing and point out it can be from a table driven source, a recursive descent (or some other hand-crafted parser) or in the Client. The Context class is used as a global entry point for the Interpreter. It’s probably heresy to do so, but I decided to put the parser in the Context. The Client sends the request to the Context and indirectly to the IAbstractExpression. The Context class still acts as a global entry point, but it also parses the data (statement in PostScript notation), but the Terminal Expression class acts more as a residual error-catcher than a terminal for multiple interpreted segments of a phrase. I don’t see it as adding tighter coupling. (If the parser were placed in the Client, I suppose it would be a purer version of the design pattern. The Client does, however, convert the string into an array using the preg_split() function; so, some partial parsing is done by the Client. The operators are treated as separate NonterminalExpression objects used to calculate the previous two elements on the stack (array). As such, they act as one-word interpreters.

The good news is that this implementation of the design pattern is wonderfully flexible and easy to update. If I wanted to change the language example from a postfix one to something like Scheme, the pattern would be able to handle it with ease. Of course, the purpose here is to examine the pattern with an illustration of its use, and while this implementation is basic, it’s a starting point.

Building a PostScript Learning Tool

The basic sequence for this little PostScript calculator is based on each the request passed from the HTML UI to the Client. It has the following sequence:

  1. User enters a string of two numbers and an operator in HTML UI.
  2. Client passes string to private variable and unsets superglobal
  3. Client converts string into a 3-element array and passes it to Context
  4. Context determines the correct expression class and returns class instance to Client
  5. Client removes the operator from the array and passes array through interpret() method of the object received from the Client.
  6. The expression class (IAbExpression implementation) carries out PHP (infix) math operation and returns result to Client
  7. Output displayed in iframe of HTML UI

Now having seen the sequence, Figure 2 shows the file diagram of the application:

Figure 2: File Diagram of Interpreter implementation

Figure 2: File Diagram of Interpreter implementation

I set the ValueTermExp.php file off to the side since it’s implemented more as an error message sender than its true role as a terminal expression. With a more sophisticated PostScript calculator (one that can handle a series of expressions), it can be upgraded to return the full calculation of the multiple NonTerminal classes.
Continue reading ‘PHP Interpreter Design Pattern’

Share

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:

< !DOCTYPE html>
<html>
<head>
    <link type="text/css" rel="stylesheet" href="tech.css"/>
    <title>Unsetting Superglobals with Classes and Methods</title>
</head>
 
<body>
    <h3>Classes and Methods</h3>
<form name="alpha" action="Client.php" method="post" target="feedback">
    Choose color from the color window:<br />
    <input type="hidden" name="class" value="ColorClass"/>
    <input type="hidden" name="method" value="doColor"/><br />
    <input type="color" name="colorNow" value="#cc0000"/>
    <p>
    <input type="submit" value="Get Color"/>
    </p> 
</form>
<form name="beta" action="Client.php" method="post" target="feedback">
    Divide or modulo the following two numbers:<br />
    <input type="hidden" name="class" value="MathClass"/>
    First:&nbsp;<input type="number" name="first" value=2/>&nbsp;
    &nbsp;Second:&nbsp;<input type="number" name="second" value=7/>
 
    <br /><input type="radio" name="method" value="doDivide"/>
    &nbsp;Divide the second by the first<br />
    <input type="radio" name="method" value="doModulo" checked=true/>
    &nbsp;Modulo the second by the first<br />
    <p>
    <input type="submit" value="Do Math"/>
    </p> 
</form>
<iframe name="feedback">feedback</iframe>
</body>
</html>

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’

Share

PHP Observer Design Pattern: The SplObserver

splObserverThe Standard PHP Library

For those of you in the Boston PHP 200 Days of Coding Advanced group and for those of you who develop with design patterns, you may have noticed that I have not taken advantage of PHP’s Standard Library (SPL). In part that’s because I don’t think about it, and the other is that often I have other features for the interface I’d like to add that are not in the SPL version. Further, there are only a couple, the Iterator that Larry talks about in his book, and the Observer pattern that I’m going to discuss in this post and on April 22 at Microsoft’s NERD Center next to the MIT campus.

In an earlier post on the Observer design pattern I noted that in a future post, I’d take a look at the built-in SplObserver and SplSubject interfaces. So as promised, here it is.

The class diagram is slightly different than the original, and to indicate the built-in interfaces, the backgrounds are filled with a light tint indicating, there’s nothing for you to add. If you compare Figure 1 with the class diagram in the other Observer pattern post, you can see certain fundamental differences:

Figure 1: Observer Class diagram with SPL Interfaces

Figure 1: Observer Class diagram with SPL Interfaces

With no abstract classes as part of the interface, everything passed to the concrete Subject and Observer is going to have to be implemented. With the Subject, that means implementing the notify() method and not having some protected properties, but otherwise, there’s not a lot of differences in the structure of the SplObserver and the Observer (from scratch.)

One Message: Lots of Ways to Configure the Message

Some developers treat the Observer design pattern like a magazine subscription—one magazine; lots of subscribers. I suppose that’s a legitimate use of the Observer, but it’s very expensive. Each concrete observer must be instantiated as a unique object. While the Subject (or SplSubject) supplies the data; the observers generally create something with that data; not just look at it. So, I decided to make a simple translation simulator. A club (like any of the many PHP groups in the world) has announcements, but rather than using the Observer for sending out notifications to subscribers, I created Observers who translated the event message from English to their own language. The concrete observers are named for their languages. But to get going, play the example and download the PHP code:
PlayDownload

When you test play the app, you’ll see that the all of the checkboxes on the left are checked and the text box is filled in with an event. Likewise, the data and day inputs are set to April and 22. You can just click the “Send Announcement” button to see the results. If you change the event to something other than “200 Days of Code” the only change you’ll see is in the English version. The other ones are only a simulation of a translation except for the month—they are actually translated. The idea would be to use a translation Web service to do the actual translations.

Beginning with the implementation of the SplSubject (ClubEvents), you can see the three abstract methods have been implemented using the signature from the SplMethod interface. (Their abstract form is shown at the top as comments.)

< ?php
class ClubEvents implements SplSubject
{
    /*Built-in abstract methods
     *abstract public void attach ( SplObserver $observer )
     *abstract public void detach ( SplObserver $observer )
     *abstract public void notify ( void )
    */
    private $member;
    private $observerSet = array();
    private $content= array();
 
    //add observer
    public function attach(SplObserver $observer)
    {
        array_push($this->observerSet, $observer);
    }
 
    //remove observer
    public function detach(SplObserver $observer)
    { 
      foreach($this->observerSet as $keyNow => $valNow)
      {
        if ($valNow == $observer)
        { 
          unset($this->observerSet[$keyNow]);
        }
      }   
    }
 
    //Set event name, month and day
    public function setState(array $content)
    {
        $this->content = $content;
        $this->notify();
    }
 
    public function getState()
    {
        return $this->content;
    }
 
    //Notify "subscribers"
    public function notify()
    {
        foreach ($this->observerSet as $value)
        {
            $value->update($this);
        }
    }
}
?>

If you’re familiar with the first example of the Observer on this blog, you’ll see similarities in the concrete Subject. About the only significant difference is the fact that the notify() method is wholly implemented in the concrete class (ClubEvents) instead of the Subject abstract class. The information (or data) generated by the SplSubject comes from the Client and triggers the notify() methods by calling setState() method. So instead of looking at the Observers next, we’ll look at the Client.

The Client’s Unlikely Role

Note: A primary principle of design patterns is,

Program to the interfaces; not the implementations.

In discussing the single SplSubject implementation (ClubEvents) and the many SplObserver implementations, I’ll be referring to them by the interface name except in certain specific cases. However, the references are to any implementation of either since we must assume (correctly) that any implementation contains a certain set of methods established in the abstract parent classes built into the Standard PHP Library (SPL).
Continue reading ‘PHP Observer Design Pattern: The SplObserver’

Share