PHP
  Home arrow PHP arrow Page 2 - Overloading and Object-Oriented Progr...
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

Overloading and Object-Oriented Programming with PHP 5
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 9
    2006-10-12

    Table of Contents:
  • Overloading and Object-Oriented Programming with PHP 5
  • SPL and Interators
  • _ _call()
  • _ _autoload()

  • 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


    Overloading and Object-Oriented Programming with PHP 5 - SPL and Interators


    (Page 2 of 4 )

    In both of the preceding examples, you created objects that you wanted to behave like arrays. For the most part, you succeeded, but you still have to treat them as objects for access. For example, this works:

    $value = $obj->name;

    But this generates a runtime error:

    $value = $obj['name'];

    Equally frustrating is that you cannot use the normal array iteration methods with them. This also generates a runtime error:

    foreach($obj as $k => $v) {}

    To enable these syntaxes to work with certain objects, Marcus Boerger wrote the Standard PHP Library (SPL) extension for PHP5. SPL supplies a group of interfaces, and it hooks into the Zend Engine, which runs PHP to allow iterator and array accessor syntaxes to work with classes that implement those interfaces.

    The interface that SPL defines to handle array-style accesses is represented by the following code:

    interface ArrayAccess {
    function offsetExists($key);
    function offsetGet($key);
    function offsetSet($key, $value);
    function offsetUnset($key);
    }

    Of course, because it is defined inside the C code, you will not actually see this definition, but translated to PHP, it would appear as such.

    If you want to do away with the OO interface to Tied completely and make its access operations look like an arrays, you can replace its _ _get() and _ _set() operations as follows:

    function offsetGet($name)
    {
    $data = dba_fetch($name, $this->dbm);
    if($data) {
    return unserialize($data);
    }
    else {
    return false;
    }
    }
    function offsetExists($name)
    {
    return dba_exists($name, $this->dbm);
    }
    function offsetSet($name, $value)
    {
    return dba_replace($name, serialize($value),
    $this->dbm); } function offsetUnset($name) { return dba_delete($name, $this->dbm); }

    Now, the following no longer works because you removed the overloaded accessors:

    $obj->name = "George"; // does not work

    But you can access it like this:

    $obj['name'] = "George";

    If you want your objects to behave like arrays when passed into built-in array functions (e.g., array map()) you can implement the Iterator and IteratorAggregate interfaces, with the resultant iterator implementing the necessary interfaces to provide support for being called in functions which take arrays as parameters. Here's an example:

    interface IteratorAggregate {
    function getIterator();
    }
    interface Iterator {
    function rewind();
    function hasMore();
    function key();
    function current();
    function next();
    }

    In this case, a class stub would look like this:

    class KlassIterator implemnts Iterator {
    /* ... */
    }
    class Klass implements IteratorAggregate {
    function getIterator() {
    return new KlassIterator($this);
    }   
    /* ... */
    }

    The following example allows the object to be used not only in foreach() loops, but in for() loop as well:

    $obj = new Klass;
    for($iter = $obj->getIterator(); $iter->hasMore();
    $iter = $iter->next()) { // work with $iter->current() }

    In the database abstraction you wrote, you could modify DB_Result to be an iterator. Here is a modification of DB_Result that changes it's API to implement Iterator:

    class DB_Result {
    protected $stmt;
    protected $result = array();
    protected $rowIndex = 0;
    protected $currIndex = 0;
    protected $max = 0;
    protected $done = false;
    function __construct(DB_Statement $stmt)
    {
    $this->stmt = $stmt;
    }
    function rewind() {
    $this->currIndex = 0;
    }
    function hasMore() {
    if($this->done && $this->max ==
    $this->currIndex) { return false; } return true; } function key() { return $this->currIndex; } function current() { return $this->result[$this->currIndex]; } function next() { if($this->done && ) { return false; } $offset = $this->currIndex + 1; if(!$this->result[$offset]) { $row = $this->stmt->fetch_assoc(); if(!$row) { $this->done = true; $this->max = $this->currIndex; return false; } $this->result[$offset] = $row; ++$this->rowIndex; ++$this->currIndex; return $this; } else { ++$this->currIndex; return $this; } } }

    Additionally, you need to modify MysqlStatement to be an IteratorAggregate, so that it can be passed into foreach() and other array-handling functions. Modifying MysqlStatement only requires adding a single function, as follows:

    class MysqlStatement implements IteratorAggregate {
    function getIterator() {
    return new MysqlResultIterator($this);
    }   
    }

    If you don't want to create a separate class to be a class's Iterator, but still want the fine-grain control that the interface provides, you can of course have a single class implement both the IteratorAggregate and Iterator interfaces.

    For convenience, you can combine the Iterator and Array Access interfaces to create objects that behave identically to arrays both in internal and user-space functions. This is ideal for classes like Tied that aimed to pose as arrays. Here is a modification of the Tied class that implements both interfaces:

    class Tied implements ArrayAccess, Iterator {
    private $dbm;
    private $dbmFile;
    private $currentKey;
    function _ _construct($file = false)
    {
    $this->dbmFile = $file;
    $this->dbm = dba_popen($this->dbmFile, "w",
    "ndbm"); } function _ _destruct() { dba_close($this->dbm); } function offsetExists($name) { return dba_exists($name, $this->dbm); } function _ _offsetGet($name) { $data = dba_fetch($name, $this->dbm); if($data) { return unserialize($data); } else { return false; } } function _offsetSet($name, $value) { function offsetUnset($name) { return dba_delete($name, $this->dbm); } return dba_replace($name, serialize($value),
    $this->dbm); } function rewind() { $this->current = dba_firstkey($this->dbm); } function current() { $key = $this->currentKey; if($key !== false) { return $this->_ _get($key); } } function next() { $this->current = dba_nextkey($this->dbm); } function has_More() { return ($this->currentKey === false)?false:true; } function key() { return $this->currentKey; } }

    To add the iteration operations necessary to implement Iterator, Tied uses dba_firstkey() to rewind its position in its internal DBM file, and it uses dba_ nextkey() to iterate through the DBM file.

    With the following changes, you can now loop over a Tied object as you would a normal associative array:

    $obj = new Tied("/tmp/tied.dbm");
    $obj->foo = "Foo";
    $obj->bar = "Bar";
    $obj->barbara = "Barbara";
    foreach($a as $k => $v) {
    print "$k => $v\n";
    }

    Running this yields the following:

    foo => Foo
    counter => 2
    bar => Bar
    barbara => Barbara

    Where did that counter come from? Remember, this is a persistent hash, so counter still remains from when you last used this DBM file.

    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 4 hosted by Hostway
    Stay green...Green IT