Archive for the 'Object Communication' Category

Sandlight CMS VI: Strategy Administrative Module

admin A CMS is only as good as the administrative module, and the one provided here is fully functional based on a simple work flow. You can change the UI and work flow to best fit your own, but you have the flexibility design patterns offer; so making changes to fit your needs (or those of your customers) should not be difficult.

One of the key features of a dynamic Web page is that it can be updated easily, and by using a MySQL table and database, all of the update information can be stored in a single location (table.) Updating the page is simply a matter of updating the data in a record or by adding new records to the table. The administrative module for this CMS has the capacity to update data in an existing record, but the page presented is always the newest record. The CMS has certain drawbacks because you cannot delete records without throwing the system out of whack, but that was done for the purposes of ease of use. (Remember, you’re a programmer and can change whatever you want!)

Set the Table

Setting up the MySQL table involves three files: 1) an interface with the MySQL connection information; 2. a connection class; and a table-creation class. The following three classes: (Use your own MySQL connection information in the IConnectInfo interface.)

< ?php
//Filename: IConnectInfo.php
interface IConnectInfo
{
        const HOST ="your_host";
        const UNAME ="your_username";
        const PW ="your_pw";
        const DBNAME = "your_dbname";
        public static function doConnect();
}
?>
 
< ?php
//Filename: UniversalConnect.php
ini_set("display_errors","1");
ERROR_REPORTING( E_ALL | E_STRICT );
include_once('IConnectInfo.php');
 
class UniversalConnect implements IConnectInfo
{
        private static $server=IConnectInfo::HOST;
        private static $currentDB= IConnectInfo::DBNAME;
        private static $user= IConnectInfo::UNAME;
        private static $pass= IConnectInfo::PW;
        private static $hookup;
 
        public static function doConnect()
        {
                self::$hookup=mysqli_connect(self::$server, self::$user, self::$pass, self::$currentDB);
                try
                {     
                        self::$hookup;
                        //Uncomment following line for develop/debug
                        echo "Successful MySql connection:
"
; } catch (Exception $e) { echo "There is a problem: " . $e->getMessage(); exit(); } return self::$hookup; } } ?>   < ?php include_once('IConnectInfo.php'); include_once('UniversalConnect.php'); class CreateTable { private $drop;   public function __construct() { $this->hookup=UniversalConnect::doConnect(); $this->tableMaster="your_table_name"; $this->dropTable(); $this->makeTable(); $this->hookup->close(); }   private function dropTable() { $this->drop = "DROP TABLE IF EXISTS $this->tableMaster";   try { $this->hookup->query($this->drop) === true; printf("Old table %s has been dropped.
"
,$this->tableMaster); } catch (Exception $e) { echo "Here is why it did not work: $e->getMessage()
"
; } }   protected function makeTable() { $this->sql = "CREATE TABLE $this->tableMaster ( id SERIAL, topic NVARCHAR(24), header NVARCHAR(120), graphic NVARCHAR(60), story BLOB, PRIMARY KEY (id))"; try { $this->hookup->query($this->sql);   } catch (Exception $e) { echo 'Here is why it did not work: ', $e->getMessage(), "
"
; } echo "Table $this->tableMaster has been created successfully.
"
; } }   $worker=new CreateTable(); ?>

The connection routines have been improved upon over time, and you can find out more about it in the original post on the subject on this blog. For now, Play the application and Download the source files. (When you click the Play button, you enter the Login UI. Use the same un/pw combination from the Functional Protective Proxy post on this blog. (Hint, you can find it in the ILogin abstract class.)
PlayDownload

In creating the table at first I used the TEXT data type for a large block of text, but then decided that a BLOB type may have a slight advantage. The BLOB is a VARBINARY and TEXT is VARCHAR, and BLOB seemed to have a slight advantage. However, the advantage may be smaller than I originally thought. Check out the MySQL docs on these two data types and you can see the differences for yourself. Figure 1 shows what the editor in the administration module looks like:

Figure 1: Administrative Module Editor

Figure 1: Administrative Module Editor

From Proxy to Strategy

The login module of this CMS is based on the Proxy pattern. Now, as in previous CMS examples, the administrative module is based on a Strategy pattern. Each object in the Strategy pattern represents an algorithm to accomplish a different task. In this case, the tasks include:

  • Entering data
  • Editing data
  • Displaying data
  • Displaying a page based on stored data.

All requests go through a context relying on a Strategy interface. In this case, I used an abstract class which allowed the addition of several protected properties and a constant with the name of the table. This is all in addition to the main method in an abstract public function, the algorithm method, executeStrategy(). Following the Strategy design pattern, begin with the Context. Continue reading ‘Sandlight CMS VI: Strategy Administrative Module’

Sandlight CMS III: PHP Abstract Factory

abfacNote: This is the third in a series for developing a CMS for Sandlight Productions. Drop by the Sandlight site to see the progress so far, and be sure to check your country’s flag count!

Now that the CMS has a filter for different devices, it now needs a pattern to take care of those devices and different types of content that they will display. Previous posts on this blog used the Bridge pattern and the Factory Method pattern. However, another pattern might be more useful for all of the different things that a Content Management System (CMS) might do. A review of the series of posts on this blog for how to select a design pattern, shows the different criteria to consider. The CMS has to create different elements of a Web page for different devices and that fact must be the focal point of the consideration. The section head for Creational Patterns in Learning PHP Design Patterns, lists the Abstract Factory pattern as a creational one, but that pattern was not discussed in the book nor on this blog. It would appear to be just what this CMS needs.

The Abstract Factory Design Pattern

The Abstract Factory pattern has features for families of factories and products instead of individual factories as does the Factory Method pattern. In comparing the relatively simple Factory Method pattern with the Abstract Factory, the Abstract Factory has multiple abstract product interfaces with multiple concrete factories for the families of the products.

Figure 1 shows the the Abstract Factory class diagram, and when you look at it, try to focus on the fact that the pattern has two types of interfaces: Factory and Product. So, if you understand the Factory Method pattern, you have a starting point for appreciating the Abstract Factory:

Figure 1: Abstract Factory class diagram

Figure 1: Abstract Factory class diagram

Unlike the Factory Method pattern, the Abstract Factory includes a Client class as an integral part of the pattern. Further, the Client holds an association between both the AbstractFactory (AbsFactory) and the two AbstractProduct classes. So while it shares some of the basic Factory Method characteristics, it is clearly a different pattern than the Factory Method.

Since the Abstract Factory may appear to be daunting, the color-coded the product instantiations (dashed lines) in the file diagram (appearing in the Play window) help show where each concrete factory method calls. Experiment with different combinations of factories (devices) and products (page parts) and look at the diagram so that you can see the path. Phone instantiations are in green, Tablet in red, and Desktop in blue. Experiment with the different single products first, and then click the bottom button to see what different “pages” each device factory displays.

Implementing the Abstract Factory in PHP

To see how this implementation of the Abstract Factory design pattern works, click the Play button. You will see both the interactive Abstract Pattern tester and the of the file diagram of this implementation of the Abstract Factory for the evolving Sandlight CMS. Click the Download button to see all of the files in the diagram. For this particular post, downloading all of the files is more important than usual because there are lots of them, and rather than having listings for all in this write-up, I’ve just selected representative ones.
PlayDownload

In addition to the Abstract Factory file diagram (viewed when you click the Play button), the following quick overview of the participants’ roles and how the CMS implements the Abstract Factory explain how this implementation works:

Client client: Only uses interfaces declared by IAbFactory (interface) and IProducts (abstract classes IHeaderProduct, IImageProduct and ITextProduct.) This means that the Client can only use the classes and methods implemented from those two interface types—factory or products. In other words, it should not directly implement a product (a page element) by directly using a product independent of the factory and product interfaces. Figure 2 illustrates this point:

Figure 2: Client works through Abstract Factory implementations

Figure 2: Client works through Abstract Factory implementations

In going over the other participants below, keep in mind that the Client can only implement concrete implementations of the IAbFactory to request products (page parts for different devices.)

IAbFactory interface: Establishes the methods for the concrete factories.

  • PhoneFactory implements operations to create phone products
  • TabletFactory implements operations to create tablet products
  • DesktopFactory implements operations to create desktop products

IHeaderProduct: abstract class Establishes the method for concrete header products and adds protected property for returning completed product.

  • PhoneHeader defines phone object to be created by the PhoneFactory and
    implements the IHeaderProduct interface
  • TabletHeader defines tablet object to be created by the Tabletactory and
    implements the IHeaderProduct interface
  • DesktopHeader defines desktop object to be created by the DesktopFactory and
    implements the IHeaderProduct interface

IImageProduct: abstract class Establishes the method for concrete image and/or video products and adds protected property for returning completed product.

  • PhoneImage defines phone object to be created by the PhoneFactory and
    implements the IImageProduct interface
  • TabletImage defines tablet object to be created by the Tabletactory and
    implements the IImageProduct interface
  • DesktopImage defines desktop object to be created by the DesktopFactory and
    implements the IImageProduct interface

ITextProduct: abstract class Establishes the method for concrete text products and adds protected property for returning completed product.

  • PhoneText defines phone object to be created by the PhoneFactory and
    implements the ITextProduct interface
  • TabletText defines tablet object to be created by the Tabletactory and
    implements the ITextProduct interface
  • DesktopText defines desktop object to be created by the DesktopFactory and
    implements the ITextProduct interface

Comparing the above outline with the Abstract Factory file diagram (seen when you click the Play button) shows that the Abstract Factory is bound to the idea of a factory implementing a product. The specific classes (products) requested are never directly referenced by the Client; rather it is through a factory. The CMS application requires factories for the different device categories; Phone, Tablet and Desktop. Each factory should be able to build the necessary parts (products) for each device. In this case (and for this example) the products are a Header, Graphic and Text. Each factory can build its own version of the products; so requesting a header, for example, is through a concrete factory, and depending on which concrete factory the clients requests, it builds the appropriate product.
Continue reading ‘Sandlight CMS III: PHP Abstract Factory’

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.

?View Code SWIFT
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.

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:

?View Code HTML
< !DOCTYPE html>


    
    Unsetting Superglobals with Classes and Methods

 

    

Classes and Methods

Choose color from the color window:

Divide or modulo the following two numbers:
First:    Second:   
 Divide the second by the first
 Modulo the second by the first

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’

PHP Introduction to OOP: UI-Client-Request

clientBasicAn Easy Start

A lot of starting concepts in OOP seem designed to confuse and warn off developers who want to move up to OOP from sequential and procedural programming. This post is to give you a bit of what was presented at the NE PHP & UX Conference and to provide a simple yet clear introduction to OOP applied to PHP.

The easiest way (and least confusing) is to begin with the idea of “objects” and communication between objects. As you may know, objects are made up of classes containing “properties” and “methods.” Properties look a lot like PHP variables and methods like functions. So, think of properties as things a car has–like headlights, a steering wheel and bumpers, and think of actions your car can take, like turning left and right or going forward and reverse as methods.

The “blueprint” for an object is a class, and when a class is instantiated in a variable, it becomes an object. Objects communicate with one another by access to public properties and methods.

At the 2014 NE PHP & UX Conference in Boston, I told those at my session that I’d have some materials for them, and so you can download them here. One is a folder full of examples from my session and the other is an introductory book (in draft form) for getting started in OOP for PHP users. Also, the Play buttons runs the little example program for this post.
PlayconfFilesoopBook

A Request-Fulfill Model

At the heart of OOP is some system of communication. The simplest way to think about communication between objects is a request-fulfill model. A client makes a request to an object to get something. The request can originate in the user UI, and it is passed to a client who finds the correct class and method to fulfill the request. Figure 1 shows a file diagram with an overview of this model:

Figure 1: Object communication

Figure 1: Object communication

In Figure 1, you can see that the only non-object is the CSS file (request.css), and so in a way, you’re used to making requests for an external operation if you’ve used CSS files. However, CSS files are not objects but rather depositories. Likewise, external JavaScript (.js) files can be called from HTML documents for use with Web pages, but they too are not objects.

Encapsulating HTML in a Class

With PHP, the UI is handled by HTML, but that does not mean that it cannot be encapsulated in a PHP object. Encapsulation is not accomplished by simply adding a .php extension to the file name, but rather, fully wrapping the HTML in a PHP class. The easiest way to do that is with a heredoc string. The following example shows how a fully formed HTML5 document is encapsulated:

Listing #1:

< ?php
class RequestUI
{
    private $ui;
 
    public function request()
    {
        //Heredoc wrapper
        $this->ui=< <<UI
        DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="request.css"/>
    <title>Requesttitle>
head>
 
<body>
    <h3>Mathster Mind:<br /> The UI Class & Method Requesterh3>
<form name='require' action='Client.php' method='post' target='feedback'>
    <input type='hidden' name='class' value='MathsterMind'/>&nbsp;MathsterMind Class<br />
    <input type='text' name='num' size='6'/>&nbsp;Enter value <br />
 
    <fieldset>
        <legend>Methodslegend>
    <input type='radio' name='method' value='doSquare'/>&nbsp;Square the value<br />
    <input type='radio' name='method' value='doSquareRoot'/>&nbsp;Find the squareroot of the value<br />
    fieldset><br />
    <input type='submit' name='send' value='Make Request'/>  
form>
<iframe name='feedback'>Feedbackiframe>
 
body>
html>
UI;
    echo $this->ui;
    }  
}
//Instantiate an object from the class
$worker=new RequestUI;
//Call the public method from the instantiated object
$worker->request();
?>

The key aspect of encapsulating HTML in a class is the heredoc wrapper:

//Heredoc wrapper
$this->ui=<< //HTML Code
UI;

A heredoc string begins with three less-than symbols (they look like chevrons laid on their side), the name you give the heredoc string and it ends with heredoc string name fully on the left side of the source code and terminated with a semi-colon. Typically, the heredoc string is assigned to a variable ($this->ui). The great thing about using heredoc, is that you can develop and debug your HTML document, and once it’s all ready, you just paste it into a heredoc wrapper. Now, instead of a free range chicken running around with snippets of PHP code, you have a fully encapsulated object. Thus, your UI is a PHP class with all of the possibilities and security of a well formed class. (Click below to see how requests are “caught” by a PHP client.)
Continue reading ‘PHP Introduction to OOP: UI-Client-Request’