Monthly Archive for March, 2015

PHP-MySql Universal Connection: The Try/Catch Exception Tweak

universal2In 2012, I posted a little piece on a PHP-MySql connection utility. Since the time of the original posting, I’ve used that utility again and again. It’s been used in my own applications (many of which have appeared on this blog), with my clients, and with others who I was able to help. Other than minor tweaking with the replacement of a conditional if statement with the try/catch exception, it has remained largely unchanged.

Recently, from Belgium provided some thoughtful comments for refactoring the little utility. (Being a big Salamander fan [Netflix], I listen to what the PHP folks from Belgium have to say!) His comments inspired some re-thinking, and while I made some changes, they were minor and along different lines. Download the revised version and take a look at it:
Download

Object Thinking

In developing software, I think in terms of objects and object structures. That is, rather than thinking in lines of code and statements, I find it easier to think in terms of what an object does and how it fits into a larger object structure rather than how statements are used. So, in using PHP with MySql, I tend to view connections to the database as something an object handles and I don’t need to worry about otherwise. Recently I was working on an Observer design patter using the built-in SplSubject and SplObserver. It occurred to me that the concrete subject might pull data out of a MySql database, and so I just popped a copy of the universal connect utility in the folder and it’s all set. Figure 1 illustrates it use:

Figure 1: Adding connection utility to small observer

Figure 1: Adding connection utility to small observer

The utility is very small—a single interface and class—but it’s very useful.

The Code

First of all, an interface stores connection information in constants, and as long as you’re using the same database, you can re-use the values. The single method is defined as public and static so that a single line of code can launch the method that uses the constants for connection. It is largely unchanged from the original.


//Filename: IConnectInfo.php
interface IConnectInfo
{
        const HOST ="localhost";
        const UNAME ="bart";
        const PW ="itchy";
        const DBNAME = "scratchy";
 
        public static function doConnect();
}
?>

The UniversalConnect class does all of the work for making a connection using the constants in the interface. Again, static declarations mean that the class need not be instantiated to use the method:


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;
                        //Comment out / Uncomment following line for develop/debug
                        echo "Successful MySql connection:
"
; } catch (Exception $e) { echo "There is a problem: " . $e->getMessage(); exit(); } return self::$hookup; } } ?>

The try/catch exception stops everything cold if the connection is not made, and the Exception provides the information you need to correct it. If the try is successful, it returns the connection to the client.

That’s pretty much it. During development, I like to see the Successful MySql connection message, but once everything is ready to go, I just comment it out. The following little class tests the connection and should not be included in a development folder:


include_once('UniversalConnect.php');
class UseMySQLConnect
{
        private $doConn;
 
        public function __construct()
        {
                try
                {
                        $this->doConn=UniversalConnect::doConnect();
                        echo "Succesful connection";
                        $this->doConn->close();
                }
                catch (Exception $e)
                {
                        echo "There is a problem: " . $e->getMessage();
                        exit();
                }
        }
}
$worker=new UseMySQLConnect();
?>

The line,

$this->doConn=UniversalConnect::doConnect();

takes care of all connection steps for you, and instead of having your code piled up with the same code block required by mysqli() (PHP’s improved MySql function), you just make sure the include_once makes the UniversalConnect class available, and you can use it wherever you need MySql.

PHP Visitor Design Pattern III: Traverser

phper250After going through single and double dispatch, it’s time to shift gears to the next major feature of the Visitor pattern; the Traverser. One of the most important (and often omitted) components of the Visitor design pattern is the Object Structure. In Part II the focus is on the double-dispatch, the number of elements that could be visited at once. The Object Structure is set up to collect the allowable visitors to visit the elements; however, only one element at at time can be displayed because the middle of the the foreach loop in the confirm() method contains a return statement—so as soon a the iteration begins, it ends with the return statement. (Let’s face it; it’s a pseudo-transveral.) Since Part II focuses on the double-dispatch, the number of elements that could be visited at one time is a tangental issue. This post, though, focuses squarely on the traversal process and the multiple elements that can be visited in a single process.

Updating the Visitor

In order to have all of the parts merrily humming along, a few changes are in order. Importantly, once these changes are made, all of the parts are still working and interacting together. To see what’s changed but how the structure is basically the same as the visitor in Part II focuses on the double-dispatch, the number of elements that could be visited at on, download the new set of files and test the new multiple element visitor:
PlayDownload
Right away, you will see that instead of radio buttons, the HTML5 UI uses check boxes for selecting one, two or three elements and then applies the visitors one at a time.(You can supply your own error-handling routine for selecting no elements!)

The HTML Element Array

One of the nicest attributes in HTML is the ability to treat a group of checkboxes with “element values” (elements as elements in an array). Each checkbox is given a name with empty brackets (e.g., my element[]). All of the selected (checked) checkboxes with the identical element name are automatically included in an array with the element name. You don’t have to worry about the unchecked ones as they are not included in the array passed to PHP.

?View Code HTML
< !DOCTYPE html>


    
    The Traverser


    

Traverser: Multiple Elements & Visitor Color

 Dispatch a circle
 Dispatch a square
 Dispatch a triangle
 

 

That checkbox array feature made it very easy to pass the shape class names (as strings) to the Client.

The Updated Client

The Client class is changed slightly to accept an array of shapes rather than just one as was done in Parts I and II of the Visitor series. Likewise, some steps were tightened up in the ObjectStructure class for cleaning up the traversal process.

< ?php
//Client.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');
 
class Client
{
    private static $shapeElement;
    private static $color;
    private static $package;
 
    //client request
    public static function request()
    {
      self::$shapeElement= array();
      self::$shapeElement=$_POST['shape'];
      self::$color=$_POST['color'];
      self::$package= array();
 
      $obStructure = new ObjectStructure();
      $colorVisitor= new self::$color();
 
      //Attach concrete elements to array & accept visitor
      foreach (self::$shapeElement as $shapeNow)
      {
        $obStructure->attach(new $shapeNow,$colorVisitor);
      }
 
      //Display selected shapes
      self::$package=$obStructure->getElements();
      foreach (self::$package as $colorShape)
      {
        echo $colorShape->showShape();
      }
    } 
}
Client::request();
?>

The Client calls on the traversal process using an instance of the OjbectStructure. The attach() method now has two parameters; a shape and a color. The shape is passed as a shape element generated by the foreach loop, creating a new shape with each iteration while adding the same color visitor to all shapes. Once everything has been stored in the ObjectStructure, a second loop calls the getElements() methods, which returns shapes with the appropriate color visitor.

The ObjectStructure

The ObjectStructure class is small but mighty. The Gang of Four note,

A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor.

Several choices are available to transverse the elements from the client through the object structure, but as seen, the humble (yet mighty) foreach loop handles the job elegantly and efficiently. The OjbectStructure provides the methods the client uses for traversal.

< ?php
//ObjectStructure.php
class ObjectStructure
{
    private $elements=array();
 
    public function attach(IElement $element,IVisitor $colorVis)
    {
        $element->accept($colorVis);
        array_push($this->elements,$element);
    }
 
    public function getElements()
    {
        return $this->elements;
    }  
}
?>

In Part II of the Visitor series, the attach() method only served to push the element onto an array, but here the method, now with two instead of one parameter serves double duty. First, each shape accepts (using the IElement::accept() method) the visitor. Second, each shape is added to an array, $elements. In some respects, this acts like a setter operation.

The only other method, getElements() returns the shapes with the accepted color. The client can then display them on the screen.
Continue reading ‘PHP Visitor Design Pattern III: Traverser’