Home arrow PHP arrow Page 3 - Building a Singleton Database with Restrictive Constructors in PHP 5

Adding methods: fetching rows, finding insertion IDs and more - PHP

In this third installment of a four-part series, I show you that a private constructor can be truly helpful when strictly implementing the Singleton design pattern. In this case, the pattern will be applied within a class that behaves like a simple MySQL abstraction layer, but the same concept can be extended to other classes.

TABLE OF CONTENTS:
  1. Building a Singleton Database with Restrictive Constructors in PHP 5
  2. Building a MySQL abstraction class
  3. Adding methods: fetching rows, finding insertion IDs and more
  4. Putting the MySQL driver to work
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
March 16, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

Provided that you already understood the rationale behind declaring the constructor of the previous MySQL driver private, it’s time to extend its current functionality. But how will this be done? Simply by our adding a few additional methods to it, the class will be able to establish a connection to the server, run queries and so forth, through a friendly interface.

Having explained that, below I listed the full definition of the driver, including the extra methods that will perform the aforementioned tasks:

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

Done. As you can see, at this point the above “MySQL” class not only exposes a single entry point through its Singleton “getInstance()” method, but it defines some simple methods for executing queries against the selected database, fetching and counting rows, and finding insertion IDs as well.

Also, it’s worth noting the implementation of a method called “connect()” that takes care of connecting to MySQL in a lazy way, meaning that it’ll be run once, and only when the driver performs a given query.

So far, so good. At this moment, the previous MySQL driver still isn't suitable to use in a production environment, but it definitely it looks much more functional than it did in an earlier stage. Thus, it’s time to set up an example that shows how to use it in a concrete case, so you can see how it works.

This hands-on example will be coded in the last section of the tutorial. So click on the link that appears below and keep reading.



 
 
>>> 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: