Design Patterns and PHP 5 - The Template Pattern
(Page 4 of 4 )
The Template pattern describes a class that modifies the logic of a subclass to make it complete.
You can use the Template pattern to hide all the database-specific connection parameters in the previous classes from yourself. To use the class from the preceding section, you need to constantly specify the connection parameters:
<?php
require_once 'DB.inc';
define('DB_MYSQL_PROD_USER', 'test');
define('DB_MYSQL_PROD_PASS', 'test');
define('DB_MYSQL_PROD_DBHOST', 'localhost');
define('DB_MYSQL_PROD_DBNAME', 'test');
$dbh = new DB::Mysql(DB_MYSQL_PROD_USER,
DB_MYSQL_PROD_PASS,
DB_MYSQL_PROD_DBHOST,
DB_MYSQL_PROD_DBNAME);
$stmt = $dbh->execute("SELECT now()");
print_r($stmt->fetch_row());
?>
To avoid having to constantly specify your connection parameters, you can subclass DB_Mysql and hard-code the connection parameters for the test database:
class DB_Mysql_Test extends DB_Mysql {
protected $user = "testuser";
protected $pass = "testpass";
protected $dbhost = "localhost";
protected $dbname = "test";
public function _ _construct() { }
}
Similarly, you can do the same thing for the production instance:
class DB_Mysql_Prod extends DB_Mysql {
protected $user = "produser";
protected $pass = "prodpass";
protected $dbhost = "prod.db.example.com";
protected $dbname = "prod";
public function _ _construct() { }
}
Please check back next week for the continuation of this article.
| 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. |
|
This article is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616). Check it out today at your favorite bookstore. Buy this book now.
|
|