Home arrow PHP arrow Page 4 - Design Patterns and PHP 5

The Template Pattern - PHP

Last week, we began our overview of the object-oriented features of PHP 5. This week, we will start discussing design patterns. This article, the second of several parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).

TABLE OF CONTENTS:
  1. Design Patterns and PHP 5
  2. The Adaptor Pattern
  3. More on the Adapter Pattern
  4. The Template Pattern
By: Sams Publishing
Rating: starstarstarstarstar / 14
September 28, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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.



 
 
>>> More PHP Articles          >>> More By Sams Publishing
 

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: