PHP
  Home arrow PHP arrow Page 2 - The Active Record Pattern
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

The Active Record Pattern
By: php|architect
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 15
    2005-12-22


    Table of Contents:
  • The Active Record Pattern
  • Sample Code
  • Test Independence
  • Record Creation

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    The Active Record Pattern - Sample Code
    ( Page 2 of 4 )

    Any discussion of database connectivity depends on choosing both a database and an access layer. This and the following two chapters use the popular open source database MySQL (http://www.mysql.com/) and the ADOdb (http://adodb.sf.net/) access layer. I established ADOdb as a standard in my workplace because it has excellent performance and it abstracts the Oracle OCI interface and interfaces to PostgreSQL, Sybase, MySQL, and other databases in a uniform, simple-to-use PHP API, allowing you to focus on your programming and business logic.

    Feel free to substitute you own database and access layer, as most of the concepts presented here readily port to other solutions.

    Before looking at the Active Record pattern, let's start with basic database connectivity. It's ideal to have a central, simple way to specify connection parameters (the hostname, username, password, and database) and to create a database connection object.  A Singleton (see Chapter 4) typically suffices.

    Here's a DB class with a conn() method that returns the Singleton instance of the ADOConnection class.

      // PHP5
     
    require_once 'adodb/adodb.inc.php';
     
    class DB {
     
      //static class, we do not need a constructor
       
    private function __construct() {}
        public static function conn() {
     
        static $conn;
     
        if (!$conn) {
     
          $conn = adoNewConnection('mysql');
     
          $conn->connect('localhost', 'username', 'passwd', 'database');
     
          $conn->setFetchMode(ADODB_FETCH_ASSOC);
          }
          return $conn;
        }
     
    }

    The DB class allows you to control the type of database and the connection parameters used in connecting to the database. At the top, the code includes the ADOdb library (you may need to adjust the include path to suit your environment); The DB constructor is private since there's no need to ever create an instance of DB; And the line $conn->setFetchMode (ADODB_FETCH_ASSOC) instructs the result set object to return rows as associative arrays of field_name => value. Using an associative array is an important best practice to adopt in working with databases, so your code remains unaffected (less brittle) by the ordering of fields in SELECT clauses of your SQL statements.

    As an example application, let's create an Active Record object to maintain a table of hyperlinks. Here's the SQL to create the hyperlinks table in a MySQL database:

      define('BOOKMARK_TABLE_DDL', <<<EOS
     
    CREATE TABLE `bookmark` (
     
      `id` INT NOT NULL AUTO_INCREMENT ,
     
      `url` VARCHAR( 255 ) NOT NULL ,
     
      `name` VARCHAR( 255 ) NOT NULL ,
     
      `description` MEDIUMTEXT,
     
      `tag` VARCHAR( 50 ) ,
     
      `created` DATETIME NOT NULL ,
     
      `updated` DATETIME NOT NULL ,
     
    PRIMARY KEY ( `id` )
     
    )
     
    EOS
      );



     
     
    >>> More PHP Articles          >>> More By php|architect
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek