Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu Advanced PHP Programming- P2 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (563.51 KB, 50 trang )

28
Chapter 1 Coding Styles
Compare this with the following:
<table>
<tr><td>Name</td><td>Position</td></tr>
<?php foreach ($employees as $employee) { ?>
<tr><td><? echo $employee[‘name’] ?></td><td><? echo $employee[‘position’]
?></td></tr>
<?php } ?>
</table>
The second code fragment is cleaner and does not obfuscate the HTML by unnecessari-
ly using
echo. As a note, using the <?= ?> syntax, which is identical to <?php echo ?>,
requires the use of
short_tags, which there are good reasons to avoid.
print Versus echo
print and echo are aliases for each other; that is, internal to the engine, they are indistinguishable. You
should pick one and use it consistently to make your code easier to read.
Using Parentheses Judiciously
You should use parentheses to add clarity to code.You can write this:
if($month == ‘february’) {
if($year % 4 == 0 && $year % 100 || $year % 400 == 0) {
$days_in_month = 29;
}
else {
$days_in_month = 28;
}
}
However, this forces the reader to remember the order of operator precedence in order
to follow how the expression is computed. In the following example, parentheses are
used to visually reinforce operator precedence so that the logic is easy to follow:


if($month == ‘february’) {
if((($year % 4 == 0 )&& ($year % 100)) || ($year % 400 == 0)) {
$days_in_month = 29;
}
else {
$days_in_month = 28;
}
}
You should not go overboard with parentheses, however. Consider this example:
if($month == ‘february’) {
if(((($year % 4) == 0 )&& (($year % 100) != 0)) || (($year % 400) == 0 )) {
$days_in_month = 29;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
29
Documentation
}
else {
$days_in_month = 28;
}
}
This expression is overburdened with parentheses, and it is just as difficult to decipher
the intention of the code as is the example that relies on operator precedence alone.
Documentation
Documentation is inherently important in writing quality code. Although well-written
code is largely self-documenting, a programmer must still read the code in order to
understand its function. In my company, code produced for clients is not considered
complete until its entire external application programming interface (API) and any inter-
nal idiosyncrasies are fully documented.
Documentation can be broken down into two major categories:
n

Inline comments that explain the logic flow of the code, aimed principally at peo-
ple modifying, enhancing, or debugging the code.
n
API documentation for users who want to use the function or class without read-
ing the code itself.
The following sections describe these two types of documentation.
Inline Comments
For inline code comments, PHP supports three syntaxes:
n
C-style comments—With this type of comment, everything between /* and */
is considered a comment. Here’s an example of a C-style comment:
/* This is a c-style comment
* (continued)
*/
n
C++-style comments—With this type of comment, everything on a line fol-
lowing // is considered a comment. Here’s an example of a C++-style comment:
// This is a c++-style comment
n
Shell/Perl-style comments—With this type of comment, the pound sign (#) is
the comment delimiter. Here’s an example of a Shell/Perl-style comment:
# This is a shell-style comment
In practice, I avoid using Shell/Perl-style comments entirely. I use C-style comments for
large comment blocks and C++-style comments for single-line comments.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
30
Chapter 1 Coding Styles
Comments should always be used to clarify code.This is a classic example of a worth-
less comment:
// increment i

i++;
This comment simply reiterates what the operator does (which should be obvious to
anyone reading the code) without lending any useful insight into why it is being per-
formed.Vacuous comments only clutter the code.
In the following example, the comment adds value:
// Use the bitwise “AND” operatorest to see if the first bit in $i is set
// to determine if $i is odd/even
if($i & 1) {
return true;
}
It explains that we are checking to see whether the first bit is set because if it is, the
number is odd.
API Documentation
Documenting an API for external users is different from documenting code inline. In
API documentation, the goal is to ensure that developers don’t have to look at the code
at all to understand how it is to be used.API documentation is essential for PHP
libraries that are shipped as part of a product and is extremely useful for documenting
libraries that are internal to an engineering team as well.
These are the basic goals of API documentation:
n
It should provide an introduction to the package or library so that end users can
quickly decide whether it is relevant to their tasks.
n
It should provide a complete listing of all public classes and functions, and it
should describe both input and output parameters.
n
It should provide a tutorial or usage examples to demonstrate explicitly how the
code should be used.
In addition, it is often useful to provide the following to end users:
n

Documentation of protected methods
n
Examples of how to extend a class to add functionality
Finally, an API documentation system should provide the following features to a devel-
oper who is writing the code that is being documented:
n
Documentation should be inline with code.This is useful for keeping documenta-
tion up-to-date, and it ensures that the documentation is always present.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
31
Documentation
n
The documentation system should have an easy and convenient syntax.Writing
documentation is seldom fun, so making it as easy as possible helps ensure that it
gets done.
n
There should be a system for generating beautified documentation.This means
that the documentation should be easily rendered in a professional and easy-to-
read format.
You could opt to build your own system for managing API documentation, or you
could use an existing package. A central theme throughout this book is learning to make
good decisions regarding when it’s a good idea to reinvent the wheel. In the case of
inline documentation, the
phpDocumentor project has done an excellent job of creating
a tool that satisfies all our requirements, so there is little reason to look elsewhere.
phpDocumentor is heavily inspired by JavaDoc, the automatic documentation system for
Java.
Using phpDocumentor
phpDocumentor works by parsing special comments in code.The comment blocks all
take this form:

/**
* Short Description
*
* Long Description
* @tags
*/
Short Description is a short (one-line) summary of the item described by the block.
Long Description is an arbitrarily verbose text block. Long Description allows for
HTML in the comments for specific formatting.
tags is a list of phpDocumentor tags.
The following are some important
phpDocumentor tags:
Tag Description
@package [package name] The package name
@author [author name] The author information
@var [type] The type for the var statement following the
comment
@param [type [description]] The type for the input parameters for the
function following the block
@return [type [description]] The type for the output of the function
You start the documentation by creating a header block for the file:
/**
* This is an example page summary block
*
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
32
Chapter 1 Coding Styles
* This is a longer description where we can
* list information in more detail.
* @package Primes

* @author George Schlossnagle
*/
This block should explain what the file is being used for, and it should set @package for
the file. Unless @package is overridden in an individual class or function, it will be
inherited by any other phpDocumentor blocks in the file.
Next, you write some documentation for a function. phpDocumentor tries its best to
be smart, but it needs some help. A function’s or class’s documentation comment must
immediately precede its declaration; otherwise, it will be applied to the intervening code
instead. Note that the following example specifies @param for the one input parameter
for the function, as well as @return to detail what the function returns:
/**
* Determines whether a number is prime (stupidly)
*
* Determines whether a number is prime or not in
* about the slowest way possible.
* <code>
* for($i=0; $i<100; $i++) {
* if(is_prime($i)) {
* echo “$i is prime\n”;
* }
* }
* </code>
* @param integer
* @return boolean true if prime, false elsewise
*/
function is_prime($num)
{
for($i=2; $i<= (int)sqrt($num); $i++) {
if($num % $i == 0) {
return false;

}
}
return true;
}
?>
This seems like a lot of work. Let’s see what it has bought us.You can run
phpDocumentor at this point, as follows:
phpdoc -f Primes.php -o HTML:frames:phpedit -t /Users/george/docs
Figure 1.3 shows the result of running this command.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
33
Documentation
Figure 1.3
phpdoc output for primes.php.
For a slightly more complicated example, look at this basic Employee class:
<?php
/**
* A simple class describing employees
*
* @package Employee
* @author George Schlossnagle
*/
/**
* An example of documenting a class
*/
class Employee
{
/**
* @var string
*/

var $name;
/**
* The employees annual salary
* @var number
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
34
Chapter 1 Coding Styles
*/
var $salary;
/**
* @var number
*/
var $employee_id;
/**
* The class constructor
* @param number
*/
function Employee($employee_id = false)
{
if($employee_id) {
$this->employee_id = $employee_id;
$this->_fetchInfo();
}
}
/**
* Fetches info for employee
*
* @access private
*/
function _fetchInfo()

{
$query = “SELECT name,
salary
FROM employees
WHERE employee_id = $this->employee_id”;
$result = mysql_query($query);
list($this->name, $this->department_id) = mysql_fetch_row($result);
}
/**
* Returns the monthly salary for the employee
* @returns number Monthly salary in dollars
*/
function monthlySalary()
{
return $this->salary/12;
}
}
?>
Note that _fetchInfo is @access private, which means that it will not be rendered by
phpdoc.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
35
Further Reading
Figure 1.4 demonstrates that with just a bit of effort, it’s easy to generate extremely pro-
fessional documentation.
Figure 1.4 The phpdoc rendering for Employee.
Further Reading
To find out more about phpDocumentor, including directions for availability and installa-
tion, go to the project page at www.phpdoc.org.
The Java style guide is an interesting read for anyone contemplating creating coding

standards.The official style guide is available from Sun at />docs/codeconv/html/CodeConvTOC.doc.html.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2
Object-Oriented Programming
Through Design Patterns
BY FAR THE LARGEST AND MOST HERALDED change in PHP5 is the complete revamp-
ing of the object model and the greatly improved support for standard object-oriented
(OO) methodologies and techniques.This book is not focused on OO programming
techniques, nor is it about design patterns.There are a number of excellent texts on both
subjects (a list of suggested reading appears at the end of this chapter). Instead, this chap-
ter is an overview of the OO features in PHP5 and of some common design patterns.
I have a rather agnostic view toward OO programming in PHP. For many problems,
using OO methods is like using a hammer to kill a fly.The level of abstraction that they
offer is unnecessary to handle simple tasks.The more complex the system, though, the
more OO methods become a viable candidate for a solution. I have worked on some
large architectures that really benefited from the modular design encouraged by OO
techniques.
This chapter provides an overview of the advanced OO features now available in
PHP. Some of the examples developed here will be used throughout the rest of this
book and will hopefully serve as a demonstration that certain problems really benefit
from the OO approach.
OO programming represents a paradigm shift from procedural programming, which is
the traditional technique for PHP programmers. In procedural programming, you have
data (stored in variables) that you pass to functions, which perform operations on the
data and may modify it or create new data. A procedural program is traditionally a list of
instructions that are followed in order, using control flow statements, functions, and so
on.The following is an example of procedural code:
<?php
function hello($name)

{
return “Hello $name!\n”;
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
38
Chapter 2 Object-Oriented Programming Through Design Patterns
function goodbye($name)
{
return “Goodbye $name!\n”;
}
function age($birthday) {
$ts = strtotime($birthday);
if($ts === -1) {
return “Unknown”;
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365));
}
}
$name = “george”;
$bday = “10 Oct 1973”;
echo hello($name);
echo “You are “.age($bday).” years old.\n”;
echo goodbye($name);
? >
Introduction to OO Programming
It is important to note that in procedural programming, the functions and the data are
separated from one another. In OO programming, data and the functions to manipulate
the data are tied together in objects. Objects contain both data (called attributes or proper-

ties) and functions to manipulate that data (called methods).
An object is defined by the class of which it is an instance. A class defines the attrib-
utes that an object has, as well as the methods it may employ.You create an object by
instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls
its constructor, which is a function that performs any setup operations. A class constructor
in PHP5 should be named
_ _constructor() so that the engine knows how to iden-
tify it.The following example creates a simple class named User, instantiates it, and calls
its two methods:
<?php
class User {
public $name;
public $birthday;
public function _ _construct($name, $birthday)
{
$this->name = $name;
$this->birthday = $birthday;
}
public function hello()
{
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
39
Introduction to OO Programming
return “Hello $this->name!\n”;
}
public function goodbye()
{
return “Goodbye $this->name!\n”;
}
public function age() {

$ts = strtotime($this->birthday);
if($ts === -1) {
return “Unknown”;
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365)) ;
}
}
}
$user = new User(‘george’, ‘10 Oct 1973’);
echo $user->hello();
echo “You are “.$user->age().” years old.\n”;
echo $user->goodbye();
?>
Running this causes the following to appear:
Hello george!
You are 29 years old.
Goodbye george!
The constructor in this example is extremely basic; it only initializes two attributes, name
and birthday.The methods are also simple. Notice that $this is automatically created
inside the class methods, and it represents the User object.To access a property or
method, you use the -> notation.
On the surface, an object doesn’t seem too different from an associative array and a
collection of functions that act on it.There are some important additional properties,
though, as described in the following sections:
n
Inheritance—Inheritance is the ability to derive new classes from existing ones
and inherit or override their attributes and methods.
n

Encapsulation—Encapsulation is the ability to hide data from users of the class.
n
Special Methods—As shown earlier in this section, classes allow for constructors
that can perform setup work (such as initializing attributes) whenever a new object
is created.They have other event callbacks that are triggered on other common
events as well: on copy, on destruction, and so on.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
40
Chapter 2 Object-Oriented Programming Through Design Patterns
n
Polymorphism—When two classes implement the same external methods, they
should be able to be used interchangeably in functions. Because fully understand-
ing polymorphism requires a larger knowledge base than you currently have, we’ll
put off discussion of it until later in this chapter, in the section “Polymorphism.”
Inheritance
You use inheritance when you want to create a new class that has properties or behav-
iors similar to those of an existing class.To provide inheritance, PHP supports the ability
for a class to extend an existing class.When you extend a class, the new class inherits all
the properties and methods of the parent (with a couple exceptions, as described later in
this chapter).You can both add new methods and properties and override the exiting
ones. An inheritance relationship is defined with the word
extends. Let’s extend User
to make a new class representing users with administrative privileges.We will augment
the class by selecting the user’s password from an NDBM file and providing a compari-
son function to compare the user’s password with the password the user supplies:
class AdminUser extends User{
public $password;
public function _ _construct($name, $birthday)
{
parent::_ _construct($name, $birthday);

$db = dba_popen(“/data/etc/auth.pw”, “r”, “ndbm”);
$this->password = dba_fetch($db, $name);
dba_close($db);
}
public function authenticate($suppliedPassword)
{
if($this->password === $suppliedPassword) {
return true;
}
else {
return false;
}
}
}
Although it is quite short, AdminUser automatically inherits all the methods from
User, so you can call hello(), goodbye(),andage(). Notice that you must manual-
ly call the constructor of the parent class as
parent::_ _constructor(); PHP5 does
not automatically call parent constructors.
parent is as keyword that resolves to a class’s
parent class.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
41
Introduction to OO Programming
Encapsulation
Users coming from a procedural language or PHP4 might wonder what all the public
stuff floating around is.Version 5 of PHP provides data-hiding capabilities with public,
protected, and private data attributes and methods.These are commonly referred to as
PPP (for public, protected, private) and carry the standard semantics:
n

Public—A public variable or method can be accessed directly by any user of the
class.
n
Protected—A protected variable or method cannot be accessed by users of the
class but can be accessed inside a subclass that inherits from the class.
n
Private—A private variable or method can only be accessed internally from the
class in which it is defined.This means that a private variable or method cannot be
called from a child that extends the class.
Encapsulation allows you to define a public interface that regulates the ways in which
users can interact with a class.You can refactor, or alter, methods that aren’t public, with-
out worrying about breaking code that depends on the class.You can refactor private
methods with impunity.The refactoring of protected methods requires more care, to
avoid breaking the classes’ subclasses.
Encapsulation is not necessary in PHP (if it is omitted, methods and properties are
assumed to be public), but it should be used when possible. Even in a single-programmer
environment, and especially in team environments, the temptation to avoid the public
interface of an object and take a shortcut by using supposedly internal methods is very
high.This quickly leads to unmaintainable code, though, because instead of a simple
public interface having to be consistent, all the methods in a class are unable to be refac-
tored for fear of causing a bug in a class that uses that method. Using PPP binds you to
this agreement and ensures that only public methods are used by external code, regard-
less of the temptation to shortcut.
Static (or Class) Attributes and Methods
In addition, methods and properties in PHP can also be declared static. A static method is
bound to a class, rather than an instance of the class (a.k.a., an object). Static methods are
called using the syntax
ClassName::method(). Inside static methods, $this is not
available.
A static property is a class variable that is associated with the class, rather than with an

instance of the class.This means that when it is changed, its change is reflected in all
instances of the class. Static properties are declared with the
static keyword and are
accessed via the syntax ClassName::$property.The following example illustrates
how static properties work:
class TestClass {
public static $counter;
}
$counter = TestClass::$counter;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
42
Chapter 2 Object-Oriented Programming Through Design Patterns
If you need to access a static property inside a class, you can also use the magic keywords
self and parent, which resolve to the current class and the parent of the current class,
respectively. Using self and parent allows you to avoid having to explicitly reference
the class by name. Here is a simple example that uses a static property to assign a unique
integer ID to every instance of the class:
class TestClass {
public static $counter = 0;
public $id;
public function _ _construct()
{
$this->id = self::$counter++;
}
}
Special Methods
Classes in PHP reserve certain method names as special callbacks to handle certain
events.You have already seen _ _construct(), which is automatically called when an
object is instantiated. Five other special callbacks are used by classes: _ _get(),
_ _set(),and_ _call() influence the way that class properties and methods are

called, and they are covered later in this chapter.The other two are _ _destruct() and
_ _clone().
_ _destruct() is the callback for object destruction. Destructors are useful for clos-
ing resources (such as file handles or database connections) that a class creates. In PHP,
variables are reference counted.When a variable’s reference count drops to 0, the variable is
removed from the system by the garbage collector. If this variable is an object, its
_ _destruct() method is called.
The following small wrapper of the PHP file utilities showcases destructors:
class IO {
public $fh = false;
public function _ _construct($filename, $flags)
{
$this->fh = fopen($filename, $flags);
}
public function _ _destruct()
{
if($this->fh) {
fclose($this->fh);
}
}
public function read($length)
{
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
43
Introduction to OO Programming
if($this->fh) {
return fread($this->fh, $length);
}
}
/* */

}
In most cases, creating a destructor is not necessary because PHP cleans up resources at
the end of a request. For long-running scripts or scripts that open a large number of
files, aggressive resource cleanup is important.
In PHP4, objects are all passed by value.This meant that if you performed the follow-
ing in PHP4:
$obj = new TestClass;
$copy = $obj;
you would actually create three copies of the class: one in the constructor, one during
the assignment of the return value from the constructor to $copy, and one when you
assign $copy to $obj.These semantics are completely different from the semantics in
most other OO languages, so they have been abandoned in PHP5.
In PHP5, when you create an object, you are returned a handle to that object, which
is similar in concept to a reference in C++.When you execute the preceding code
under PHP5, you only create a single instance of the object; no copies are made.
To actually copy an object in PHP5, you need to use the built-in _ _clone()
method. In the preceding example, to make $copy an actual copy of $obj (and not just
another reference to a single object), you need to do this:
$obj = new TestClass;
$copy = $obj->_ _clone();
For some classes, the built-in deep-copy _ _clone() method may not be adequate for
your needs, so PHP allows you to override it. Inside the _ _clone() method, you not
only have $this, which represents the new object, but also $that, which is the object
being cloned. For example, in the TestClass class defined previously in this chapter, if
you use the default _ _clone() method, you will copy its id property. Instead, you
should rewrite the class as follows:
class TestClass {
public static $counter = 0;
public $id;
public $other;

public function _ _construct()
{
$this->id = self::$counter++;
}
public function _ _clone()
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
44
Chapter 2 Object-Oriented Programming Through Design Patterns
{
$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
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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 procedural 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)) {
throw new Exception;
}
if(!mysql_select_db($this->dbname, $this->dbh)) {
throw new Exception;
}
}
public function execute($query) {

if(!$this->dbh) {
$this->connect();
}
$ret = mysql_query($query, $this->dbh);
if(!$ret) {
throw new Exception;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
46
Chapter 2 Object-Oriented Programming Through Design Patterns
}
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_Mysql object 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_MysqlStatement object, 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;
}
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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() and mysql_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 variables
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
mysqli extension.

To accomplish this, you need to modify DB_Mysql to include a prepare method
and DB_MysqlStatement to include bind and execute methods:
class DB_Mysql {
/* */
public function prepare($query) {
if(!$this->dbh) {
$this->connect();
}
return new DB_MysqlStatement($this->dbh, $query);
}
}
class DB_MysqlStatement {
public $result;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
48
Chapter 2 Object-Oriented Programming Through Design Patterns
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_MysqlStatement object 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 :1 in the query says that this is the location of the first bind variable.When you call
the execute() 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 :1 in 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.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
49

A Brief Introduction to Design Patterns
The Template Pattern
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 parame-
ters 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 purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
50
Chapter 2 Object-Oriented Programming Through Design Patterns
Polymorphism
The database wrappers developed in this chapter are pretty generic. In fact, if you look at
the other database extensions built in to PHP, you see the same basic functionality over
and over again—connecting to a database, preparing queries, executing queries, and
fetching back the results. If you wanted to, you could write a similar DB_Pgsql or
DB_Oracle class that wraps the PostgreSQL or Oracle libraries, and you would have
basically the same methods in it.
In fact, although having basically the same methods does not buy you anything, hav-
ing identically named methods to perform the same sorts of tasks is important. It allows
for polymorphism, which is the ability to transparently replace one object with another
if their access APIs are the same.
In practical terms, polymorphism means that you can write functions like this:
function show_entry($entry_id, $dbh)
{
$query = “SELECT * FROM Entries WHERE entry_id = :1”;

$stmt = $dbh->prepare($query)->execute($entry_id);
$entry = $stmt->fetch_row();
// display entry
}
This function not only works if $dbh is a DB_Mysql object, but it works fine as long as
$dbh implements a prepare() method and that method returns an object that imple-
ments the execute() and fetch_assoc() methods.
To avoid passing a database object into every function called, you can use the concept
of delegation. Delegation is an OO pattern whereby an object has as an attribute another
object that it uses to perform certain tasks.
The database wrapper libraries are a perfect example of a class that is often delegated
to. In a common application, many classes need to perform database operations.The
classes have two options:
n
You can implement all their database calls natively.This is silly. It makes all the
work you’ve done in putting together a database wrapper pointless.
n
You can use the database wrapper API but instantiate objects on-the-fly. Here is an
example that uses this option:
class Weblog {
public function show_entry($entry_id)
{
$query = “SELECT * FROM Entries WHERE entry_id = :1”;
$dbh = new Mysql_Weblog();
$stmt = $dbh->prepare($query)->execute($entry_id);
$entry = $stmt->fetch_row();
// display entry
}
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

51
A Brief Introduction to Design Patterns
On the surface, instantiating database connection objects on-the-fly seems like a
fine idea; you are using the wrapper library, so all is good.The problem is that if
you need to switch the database this class uses, you need to go through and change
every function in which a connection is made.
n
You implement delegation by having Weblog contain a database wrapper object as
an attribute of the class.When an instance of the class is instantiated, it creates a
database wrapper object that it will use for all input/output (I/O). Here is a re-
implementation of Weblog that uses this technique:
class Weblog {
protected $dbh;
public function setDB($dbh)
{
$this->dbh = $dbh;
}
public function show_entry($entry_id)
{
$query =
“SELECT * FROM Entries WHERE entry_id = :1”;
$stmt = $this->dbh->prepare($query)->execute($entry_id);
$entry = $stmt->fetch_row();
// display entry
}
}
Now you can set the database for your object, as follows:
$blog = new Weblog;
$dbh = new Mysql_Weblog;
$blog->setDB($dbh);

Of course, you can also opt to use a Template pattern instead to set your database dele-
gate:
class Weblog_Std extends Weblog {
protected $dbh;
public function _ _construct()
{
$this->dbh = new Mysql_Weblog;
}
}
$blog = new Weblog_Std;
Delegation is useful any time you need to perform a complex service or a service that is
likely to vary inside a class. Another place that delegation is commonly used is in classes
that need to generate output. If the output might be rendered in a number of possible
ways (for example, HTML, RSS [which stands for Rich Site Summary or Really Simple
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
52
Chapter 2 Object-Oriented Programming Through Design Patterns
Syndication, depending on who you ask], or plain text), it might make sense to register a
delegate capable of generating the output that you want.
Interfaces and Type Hints
A key to successful delegation is to ensure that all classes that might be dispatched to are
polymorphic. If you set as the $dbh parameter for the Weblog object a class that does
not implement fetch_row(), a fatal error will be generated at runtime. Runtime error
detection is hard enough, without having to manually ensure that all your objects imple-
ment all the requisite functions.
To help catch these sorts of errors at an earlier stage, PHP5 introduces the concept of
interfaces. An interface is like a skeleton of a class. It defines any number of methods, but
it provides no code for them—only a prototype, such as the arguments of the function.
Here is a basic
interface that specifies the methods needed for a database connection:

interface DB_Connection {
public function execute($query);
public function prepare($query);
}
Whereas you inherit from a class by extending it, with an interface, because there is no
code defined, you simply agree to implement the functions it defines in the way it
defines them.
For example,
DB_Mysql implements all the function prototypes specified by
DB_Connection, so you could declare it as follows:
class DB_Mysql implements DB_Connection {
/* class definition */
}
If you declare a class as implementing an interface when it in fact does not, you get a
compile-time error. For example, say you create a class
DB_Foo that implements neither
method:
<?php
require “DB/Connection.inc”;
class DB_Foo implements DB_Connection {}
?>
Running this class generates the following error:
Fatal error: Class db_foo contains 2 abstract methods and must
be declared abstract (db connection::execute, db connection:: prepare)
in /Users/george/Advanced PHP/examples/chapter-2/14.php on line 3
PHP does not support multiple inheritance.That is, a class cannot directly derive from
more than one class. For example, the following is invalid syntax:
class A extends B, C {}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×