• No results found

The Adaptor Pattern

In document Sams - Advanced Php Programming (Page 67-72)

$this->other = $that->other;

$this->id = self::$counter++;

} }

A Brief Introduction to Design Patterns

You have likely heard of design patterns, but you might not know what they are. Design patterns are generalized solutions to classes of problems that software developers

encounter frequently.

If you’ve programmed for a long time, you have most likely needed to adapt a library to be accessible via an alternative API.You’re not alone.This is a common problem, and although there is not a general solution that solves all such problems, people have recog-nized this type of problem and its varying solutions as being recurrent.The fundamental idea of design patterns is that problems and their corresponding solutions tend to follow repeatable patterns.

Design patterns suffer greatly from being overhyped. For years I dismissed design pat-terns without real consideration. My problems were unique and complex, I thought—

they would not fit a mold.This was really short-sighted of me.

Design patterns provide a vocabulary for identification and classification of problems.

In Egyptian mythology, deities and other entities had secret names, and if you could dis-cover those names, you could control the deities’ and entities’ power. Design problems are very similar in nature. If you can discern a problem’s true nature and associate it with a known set of analogous (solved) problems, you are most of the way to solving it.

To claim that a single chapter on design patterns is in any way complete would be ridiculous.The following sections explore a few patterns, mainly as a vehicle for show-casing some of the advanced OO techniques available in PHP.

The Adaptor Pattern

The Adaptor pattern is used to provide access to an object via a specific interface. In a purely OO language, the Adaptor pattern specifically addresses providing an alternative API to an object; but in PHP we most often see this pattern as providing an alternative interface to a set of procedural routines.

Providing the ability to interface with a class via a specific API can be helpful for two main reasons:

n If multiple classes providing similar services implement the same API, you can switch between them at runtime.This is known as polymorphism.This is derived from Latin: Poly means “many,” and morph means “form.”

n A predefined framework for acting on a set of objects may be difficult to change.

When incorporating a third-party class that does not comply with the API used by the framework, it is often easiest to use an Adaptor to provide access via the

45 A Brief Introduction to Design Patterns

expected API.

The most common use of adaptors in PHP is not for providing an alternative interface to one class via another (because there is a limited amount of commercial PHP code, and open code can have its interface changed directly). PHP has its roots in being a pro-cedural language; therefore, most of the built-in PHP functions are propro-cedural in nature.

When functions need to be accessed sequentially (for example, when you’re making a database query, you need to use mysql_pconnect(),mysql_select_db(),

mysql_query(), andmysql_fetch()), a resource is commonly used to hold the con-nection data, and you pass that into all your functions.Wrapping this entire process in a class can help hide much of the repetitive work and error handling that need to be done.

The idea is to wrap an object interface around the two principal MySQL extension resources: the connection resource and the result resource.The goal is not to write a true abstraction but to simply provide enough wrapper code that you can access all the MySQL extension functions in an OO way and add a bit of additional convenience.

Here is a first attempt at such a wrapper class:

class DB_Mysql { protected $user;

protected $pass;

protected $dbhost;

protected $dbname;

protected $dbh; // Database connection handle

public function _ _construct($user, $pass, $dbhost, $dbname) {

$this->user = $user;

$this->pass = $pass;

$this->dbhost = $dbhost;

$this->dbname = $dbname;

}

protected function connect() {

$this->dbh = mysql_pconnect($this->dbhost, $this->user, $this->pass);

if(!is_resource($this->dbh)) {

public function execute($query) { if(!$this->dbh) {

$this->connect();

}

$ret = mysql_query($query, $this->dbh);

if(!$ret) {

throw new Exception;

}

else if(!is_resource($ret)) { return TRUE;

} else {

$stmt = new DB_MysqlStatement($this->dbh, $query);

$stmt->result = $ret;

return $stmt;

} } }

To use this interface, you just create a new DB_Mysqlobject and instantiate it with the login credentials for the MySQL database you are logging in to (username, password, hostname, and database name):

$dbh = new DB_Mysql(testuser, testpass, localhost, testdb);

$query = SELECT * FROM users WHERE name = ‘“.mysql_escape_string($name).”‘“;

$stmt = $dbh->execute($query);

This code returns a DB_MysqlStatementobject, which is a wrapper you implement around the MySQL return value resource:

class DB_MysqlStatement { protected $result;

public $query;

protected $dbh;

public function _ _construct($dbh, $query) {

$this->query = $query;

$this->dbh = $dbh;

if(!is_resource($dbh)) {

throw new Exception(Not a valid database connection);

} }

public function fetch_row() { if(!$this->result) {

throw new Exception(Query not executed);

}

return mysql_fetch_row($this->result);

}

public function fetch_assoc() {

return mysql_fetch_assoc($this->result);

}

public function fetchall_assoc() {

$retval = array();

while($row = $this->fetch_assoc()) {

$retval[] = $row;

}

return $retval;

} }

47 A Brief Introduction to Design Patterns

To then extract rows from the query as you would by using mysql_fetch_assoc(), you can use this:

while($row = $stmt->fetch_assoc()) { // process row

}

The following are a few things to note about this implementation:

n It avoids having to manually call connect()andmysql_select_db().

n It throws exceptions on error. Exceptions are a new feature in PHP5.We won’t discuss them much here, so you can safely ignore them for now, but the second half of Chapter 3, “Error Handling,” is dedicated to that topic.

n It has not bought much convenience.You still have to escape all your data, which is annoying, and there is no way to easily reuse queries.

To address this third issue, you can augment the interface to allow for the wrapper to automatically escape any data you pass it.The easiest way to accomplish this is by provid-ing an emulation of a prepared query.When you execute a query against a database, the raw SQL you pass in must be parsed into a form that the database understands internally.

This step involves a certain amount of overhead, so many database systems attempt to cache these results. A user can prepare a query, which causes the database to parse the query and return some sort of resource that is tied to the parsed query representation. A feature that often goes hand-in-hand with this is bind SQL. Bind SQL allows you to parse a query with placeholders for where your variable data will go.Then you can bind parameters to the parsed version of the query prior to execution. On many database sys-tems (notably Oracle), there is a significant performance benefit to using bind SQL.

Versions of MySQL prior to 4.1 do not provide a separate interface for users to pre-pare queries prior to execution or allow bind SQL. For us, though, passing all the vari-able data into the process separately provides a convenient place to intercept the varivari-ables and escape them before they are inserted into the query. An interface to the new MySQL 4.1 functionality is provided through Georg Richter’s mysqliextension.

To accomplish this, you need to modify DB_Mysqlto include a preparemethod andDB_MysqlStatementto include bindandexecutemethods:

class DB_Mysql { /* ... */

public function prepare($query) { if(!$this->dbh) {

$this->connect();

}

return new DB_MysqlStatement($this->dbh, $query);

} }

class DB_MysqlStatement { public $result;

public $binds;

public $query;

public $dbh;

/* ... */

public function execute() {

$binds = func_get_args();

foreach($binds as $index => $name) {

$this->binds[$index + 1] = $name;

}

$cnt = count($binds);

$query = $this->query;

foreach ($this->binds as $ph => $pv) {

$query = str_replace(:$ph, “‘“.mysql_escape_string($pv).”‘“, $query);

}

$this->result = mysql_query($query, $this->dbh);

if(!$this->result) { throw new MysqlException;

}

return $this;

}

/* ... */

}

In this case, prepare()actually does almost nothing; it simply instantiates a new DB_MysqlStatementobject with the query specified.The real work all happens in DB_MysqlStatement. If you have no bind parameters, you can just call this:

$dbh = new DB_Mysql(testuser, testpass, localhost, testdb);

$stmt = $dbh->prepare(SELECT * FROM users

WHERE name = ‘“.mysql_escape_string($name).”‘“);

$stmt->execute();

The real benefit of using this wrapper class rather than using the native procedural calls comes when you want to bind parameters into your query.To do this, you can embed placeholders in your query, starting with :, which you can bind into at execution time:

$dbh = new DB_Mysql(testuser, testpass, localhost, testdb);

$stmt = $dbh->prepare(SELECT * FROM users WHERE name = :1);

$stmt->execute($name);

The:1in the query says that this is the location of the first bind variable.When you call theexecute()method of $stmt,execute()parses its argument, assigns its first passed argument ($name) to be the first bind variable’s value, escapes and quotes it, and then substitutes it for the first bind placeholder :1in the query.

Even though this bind interface doesn’t have the traditional performance benefits of a bind interface, it provides a convenient way to automatically escape all input to a query.

49 A Brief Introduction to Design Patterns

In document Sams - Advanced Php Programming (Page 67-72)