PHP Design patterns : Part 1 – Adapter pattern

The Adapter pattern is used to provide access to an object via a specific interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface, into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. In PHP we most often see this pattern as providing an alternative interface to a set of procedural routines such as database connect, query and retrieve routines. Wrapper classes are generally an implementation of the adapter pattern.

Example wrapper class illustrating adapter pattern:

1
2
3
4
5
6
7
8
9
10
11
class DB_Mysql
{
protected $user;
protected $pass;
protected $dbhost;
protected $dbname;
protected $dbh;
public function connect() { //implementation }
public function prepare() { //implementation }
public function execute() { //implementation }
}
1
2
3
4
5
6
7
8
9
class DB_MysqlStatement
{
protected $result;
public $query;
protected $dbh;
public function execute() { //implementation }
public function fetch_row() { //implementation }
public function fetch_assoc() { //implementation }
}

Using the above wrapper classes:

1
2
3
$dbh = new DB_Mysql(“w3user”, “w3pass”, “localhost”, “w3db”);
$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

Filed Under: PHP Design patterns

Tags:

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.