Building a Content Management System with PEAR - The PEAR::DB connection
(Page 4 of 4 )
So where does database abstraction come into play? So far we have been looking only at the database tables and the application structure. Once you've installed the PEAR::DB package, it will be available system wide. This means that you can access it from anywhere. To use DB you simply include it in your scripts and you will have access to all its functions.
For our site, we want to have a central place where we can make changes that will affect the whole site. I have created a file that will hold all the information that DB requires. This file is called "connx.php." It abstracts database access in the sense that it enables you to use any kind of database system, without actually having to install a specific driver. All that you change is the type of database driver that you prefer in your configuration script (such as connx.php).
You can see the contents of the connx.php script below:
<?php
// the hostname of the database server
// the username to connect with
// the user's password
// the name of the database to connect to
// the type of database server.
$dbhost= "localhost";
$dbuser= "root";
$dbpass= "pass";
$dbname= "cms";
$dbtype= "mysql";
// Build a DSN string (Data Source Name)
// Required by DB::connect()
$dsn = $dbtype . "://"
.$dbuser . ":"
. $dbpass . "@"
. $dbhost . "/"
. $dbname;
// Creates a database connection object in $db
// or, a database error object if it went wrong.
// The boolean specifies this is a persistent
// connection like mysql_pconnect(), it
// defaults to FALSE.
$db = DB::connect($dsn, TRUE);
// Check whether the object is a connection or
// an error.
// Print out a message and exit if it's
// an error object.
if (DB::isError($db)) {
die($db->getMessage());
}
?>
In the next article we will look at this code in detail, and also discuss the other application-wide scripts.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |