Home arrow PHP arrow Page 2 - Overloading and Object-Oriented Programming with PHP 5

SPL and Interators - PHP

Last week, we discussed design patterns and polymorphism. This week, we examine overloading and more. This article, the last of four parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).

TABLE OF CONTENTS:
  1. Overloading and Object-Oriented Programming with PHP 5
  2. SPL and Interators
  3. _ _call()
  4. _ _autoload()
By: Sams Publishing
Rating: starstarstarstarstar / 16
October 12, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: