Home arrow PHP arrow Page 2 - Creating a Static Web Form Helper with Restrictive Constructors

Review: using a private constructor in a Singleton class - PHP

Welcome to the final installment of a series that shows you how to use restrictive constructors in PHP 5. With a decent variety of code samples, this series recreates for you a few common scenarios where the implementation of both protected and private constructors can greatly improve the behavior of different classes in the context of a given application.

TABLE OF CONTENTS:
  1. Creating a Static Web Form Helper with Restrictive Constructors
  2. Review: using a private constructor in a Singleton class
  3. Building a static web form helper class with a private constructor
  4. Using the previous Form helper class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
March 23, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Before I start explaining how to use a private constructor for building a purely static web form helper, it’d be helpful to recall the example developed in the prior part of the series. That example showed how to take advantage of this handy approach when creating a basic Singleton MySQL abstraction class.

Having said that, here’s the definition of this class:

class MySQL

{

    private $_result = NULL;

    private $_link = NULL;

    private $_config = array();

    private static $_instance = NULL;

 

 

    // return Singleton instance of MySQL class

    public static function getInstance(array $config = array())

    {

        if (self::$_instance === NULL)

        {

            self::$_instance = new self($config);

        }

        return self::$_instance;

    }

   

    // private constructor

    private function __construct(array $config)

    {

        if (count($config) < 4)

        {

            throw new Exception('Invalid number of connection parameters');  

        }

        $this->_config = $config;

    }

   

    // prevent cloning class instance

    private function __clone(){}

   

    // connect to MySQL

    private function connect()

    {

        // connect only once

        static $connected = FALSE;

        if ($connected === FALSE)

        {

            list($host, $user, $password, $database) = $this->_config;

            if ((!$this->_link = mysqli_connect($host, $user, $password, $database)))

            {

                throw new Exception('Error connecting to MySQL : ' . mysqli_connect_error());

            }

            $connected = TRUE;

            unset($host, $user, $password, $database);      

        }

    }

 

 

    // perform query

    public function query($query)

    {

        if (is_string($query) and !empty($query))

        {

            // lazy connect to MySQL

            $this->connect();

            if ((!$this->_result = mysqli_query($this->_link, $query)))

            {

                throw new Exception('Error performing query ' . $query . ' Message : ' . mysqli_error($this->_link));

            }

        }

    }

   

    // fetch row from result set

    public function fetch()

    {

        if ((!$row = mysqli_fetch_object($this->_result)))

        {

            mysqli_free_result($this->_result);

            return FALSE;

        }

        return $row;

    }

 

 

    // get insertion ID

    public function getInsertID()

    {

        if ($this->_link !== NUlL)

        {

            return mysqli_insert_id($this->_link); 

        }

        return NULL;

       

    }

   

    // count rows in result set

    public function countRows()

    {

        if ($this->_result !== NULL)

        {

           return mysqli_num_rows($this->_result);

        }

        return 0;

    }

   

    // close the database connection

    function __destruct()

    {

        is_resource($this->_link) AND mysqli_close($this->_link);

    }

}// End MySQL class

Apart from studying the underlying logic of the methods implemented by the above “MySQL” class, you should pay special attention to its constructor, as it’s been declared private. Doing this means the only entry and instantiation point of the class is its static “getInstance()” method, which permits you to turn the class into a Singleton pretty easily.

And now that you understand the rationale behind using a private constructor within the previous MySQL driver, below I listed a short script that shows how to use it for fetching some user-related data from a fictional “users” table. Take a look at it:

// create instance of MySQL class

$db = MySQL::getInstance(array('host', 'user', 'password', 'database'));

// fetch users from database table

$db->query('SELECT * FROM users');

// display user data

while ($user = $db->fetch())

{

    echo 'First Name: ' . $user->fname . ' Last Name: '. $user->lname . ' Email: '. $user->email . '<br />';

}

As the previous script shows, a typical implementation of the Singleton design pattern can be reinforced thanks to the use of a restrictive constructor. On the other hand, the rest of the script is very easy to follow, so I’m not going to waste your time explaining how it works.

Well, having recreated another concrete situation where a private constructor can be really helpful, it’s time to explore other possible cases where this kind of method can be used successfully. Thus, in keeping with the concepts deployed in the introduction, in the course of the following section I’m going to show you how to create a simple -- yet functional -- HTML form helper class. It will make use of a private constructor to prevent its access within an instance context.

To learn the full details regarding the construction of this static helper, click on the link below and read the next few lines.  



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: