Tuesday, September 7th, 2010

PHP Design patterns : Part 2 – Template pattern

The Template pattern is the use of a class that inherits a class and adds functionality that can prevent redundancy in code usage.
To use the adapter class from part 1, you need to constantly specify the connection parameters to the database. To prevent specifying the database details in every php file, we can use the template pattern and extend the adapter class to create a subclass that defines the connection parameters as constants.

1
2
3
4
5
6
7
8
9
class DB_Mysql_Test extends DB_Mysql {
protected $user = “w3user”;
protected $pass = “w3pass”;
protected $dbhost = “localhost”;
protected $dbname = “articles”;
public function __construct() { //implementation using $this->user,$this->pass,$this->dbhost,$this->dbname }
// more implementation of class.
 
}

Using the above template patter wrapper classes:

1
2
3
$dbh = new DB_Mysql_Test();
$statemt = $dbh->prepare(“SELECT * FROM articles WHERE author = :1);
$statemt->execute();
Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Tags: , ,

Readers Comments (1)

  1. [...] Read the rest here: PHP Design patterns | PHP Design patterns : Part 2 – Template … [...]




Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.


Latest Additions

Popular User Submitted Links

1


Hosted & Optimized JS Libraries – Cached Commons

1


Multi-File Uploader & Resizer – Agile Uploader

1


Open source online notebook-to-do-list manager

1


3 tier app design in silverlight using azure & RIA services

1


Polymaps – A JS Library For Image & Vector-Tiled Maps

eXTReMe Tracker