As I anticipated in the section that you just finished reading, I coded a short script below that shows how to use the previous MySQL driver to pull some records from a “users” table and display the data on screen. Take a look at it: <?php
try { // connect to MySQL $db = MySQLiWrapper::getInstance(array('host', 'user', 'password', 'database'));
// fetch users from database $users = $db->runQuery('SELECT * FROM users');
// display user data foreach ($users as $user) { echo 'First Name: ' . $user->fname . ' Last Name: ' . $user->lname . '<br />'; } } // catch exceptions catch(Exception $e) { echo $e->getMessage(); exit(); } As seen before, once a Singleton instance of the driver has been properly grabbed via the static “getInstance()” method, the object is then used for fetching user-related data from a fictional database table. Finally, the retrieved result set is traversed by using a simple “foreach” construct. Even when for obvious reasons, the static $_property is hidden behind the class’ API, this code fragment shows in a nutshell how useful this property can be for building a Singleton MySQL abstraction class. But as you may have guessed, there are many other possible uses for static class variables. For the moment, though, go ahead and read the conclusions below. Final thoughts This is it for now. In this second part of the series, I finished building this sample MySQL driver by adding to it a whole new class responsible for iterating over database result sets through a friendly and intuitive API. This functional example showed that the use of a simple static property makes it easier to implement the Singleton pattern, which is convenient when developing a class that abstracts the access to a database server, be it MySQL or a different one. In the tutorial to come, I’m going to show you how to improve the behavior of this driver even further, specifically when connecting to MySQL, by using yet another static property. Want to see how this will be done? Then don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|