PHP
  Home arrow PHP arrow Page 4 - The Active Record Pattern, concluded
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, concluded
By: php|architect
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2005-12-29


    Table of Contents:
  • The Active Record Pattern, concluded
  • Active Record Instance ID
  • Searching for Records
  • Updating Records
  • Issues

  • 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, concluded - Updating Records
    ( Page 4 of 5 )

    The Create and Read portions of CRUD are complete; what about Update? It makes sense to use save() to update an Active Record object, but as it is now, save() only handles INSERT statements. To recap, save() looks like this:

    class Bookmark{
      // ...
      const INSERT_SQL = “
        insert into bookmark (url, name, description, 
          tag, created, updated)
        values (?, ?, ?, ?, now(), now())
        “;
      protected function save() {
        $rs = $this->conn->execute(
          self::INSERT_SQL
          ,array($this->url, $this->name, 
            $this->description, $this->tag));
        if ($rs) {
          $this->id = (int)$this->conn->Insert_ID();
        } else {
          trigger_error(‘DB Error: ‘.$this->conn->errorMsg());
        }
      }
    }

    However, after you already have a valid instance, you would rather see something like:

    class Bookmark {
      // ...
      const UPDATE_SQL = “
        update bookmark set
          url = ?,
          name = ?,
          description = ?,
          tag = ?,
          updated = now()
        where id = ?
        “;
      public function save() {
        $this->conn->execute(
          self::UPDATE_SQL
          ,array(
            $this->url,
            $this->name,
            $this->description,
            $this->tag,
            $this->id));
      }
    }

    To differentiate between INSERT and UPDATE, you need to detect if a bookmark is new or if it’s been loaded from the database.  

    First, refactor the two “versions” of save() into individual protected methods with the descriptive names insert() and update().

    class Bookmark {
      // ...
      protected function insert() {
        $rs = $this->conn->execute(
          self::INSERT_SQL
          ,array($this->url, $this->name, 
            $this->description, $this->tag));
        if ($rs) {
          $this->id = (int)$this->conn->Insert_ID();
        }
      }
      protected function update() {
          $this->conn->execute(
            self::UPDATE_SQL
            ,array(
              $this->url,
              $this->name,
              $this->description,
              $this->tag,
              $this->id));
      }
    }

    Now you can change save() to look at this info:

    class Bookmark {
      const NEW_BOOKMARK = -1;
      protected $id = Bookmark::NEW_BOOKMARK;
      // ...
      public function save() {
        if ($this->id == Bookmark::NEW_BOOKMARK) {
          $this->insert();
        } else {
          $this->update();
        }
      }
    }

    Just one last issue: timestamps change in the database whenever you insert or update a record. There is no other way to keep an accurate timestamp in the Bookmark other than making another trip to the database to retrieve it. Since this applies to either inserts or updates, change the Active Record class to always update the timestamp before leaving the save() method in order to prevent the latter from getting out of sync.

    class Bookmark {
      // ...
      public function save() {
        if ($this->id == self::NEW_BOOKMARK) {
          $this->insert();
        } else {
          $this->update();
        }
        $this->setTimeStamps();
      }
      protected function setTimeStamps() {
        $rs = $this->conn->execute(
          self::SELECT_BY_ID
          ,array($this->id));
        if ($rs) {
          $row = $rs->fetchRow();
          $this->created = $row[‘created’];
          $this->updated = $row[‘updated’];
        }
      }
    }

    Bookmark gets to the heart of the ActiveRecord pattern: save() knows the SQL statement required to update or insert into the database table, knows the object’s current state, and can assemble the needed parameter substitution array from the object’s own attributes.  Let’s test it:

    class ActiveRecordTestCase extends UnitTestCase {
      // ...
      function testSave() {
        $link = Bookmark::add(
          ‘http://blog.casey-sweat.us/’,
          ‘My Blog’,
          ‘Where I write about stuff’,
          ‘php’);
        $link->description = 
          ‘Where I write about PHP, Linux and other stuff’;
        $link->save();
        $link2 = Bookmark($link->getId());
        $this->assertEqual($link->getId(), $link2->getId());
        $this->assertEqual($link->created, $link2->updated);
      }
    }

    For now, let’s skip how to implement DELETE. There is an example in Chapter 16—The Data Mapper Pattern, but you can easily derive it from the insert() and update() methods.



     
     
    >>> 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 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek