PHP
  Home arrow PHP arrow Page 3 - Design Patterns and PHP 5
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Design Patterns and PHP 5
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 10
    2006-09-28

    Table of Contents:
  • Design Patterns and PHP 5
  • The Adaptor Pattern
  • More on the Adapter Pattern
  • The Template Pattern

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Design Patterns and PHP 5 - More on the Adapter Pattern


    (Page 3 of 4 )

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

    • It avoids having to manually call connect() and mysql_select_db().

    • 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.

    • 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 providing 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 systems (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 prepare queries prior to execution or allow bind SQL. For us, though, passing all the variable 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;
    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.

    More PHP Articles
    More By Sams Publishing


       · This article is an excerpt from the book "Advanced PHP Programming," published by...
     

    Buy this book now. This article is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616). Check it out today at your favorite bookstore. Buy this book now.

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT