Home arrow PHP arrow Lazy Loading with External PHP Iterators

Lazy Loading with External PHP Iterators

Let’s face it: building custom external iterators is one of those things that we, as PHP developers, have to tackle sooner or later. Whether it comes to iterating over database result sets or traversing plain array elements, external iterators are powerful, reusable structures that permit you to develop more efficient object-oriented applications. This is the third part in our series on external iterators in PHP.

TABLE OF CONTENTS:
  1. Lazy Loading with External PHP Iterators
  2. Building File Helpers in PHP
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
April 06, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

The fun side of outer iterators (at least when using an OOP approach) is that their implementation is (in most cases) a straightforward process that can be mastered in a snap. Of course, claming this without  concrete proof would be rather pointless. In line with this idea, in previous installments of this series I went through the development of a couple of concrete examples that demonstrated how to use an external iterator for traversing the protected fields of a class whose primary use was to model generic entities.

In the first tutorial, the whole traversing task was performed via a custom array collection, while the second how-to achieved the same process through the native ArrayIterator class bundled with the SPL. In both cases, the results were nearly identical, even though the use of a built-in class like ArrayIterator, saved us from the hassles of having to write an array wrapper all by ourselves. You find both tutorials here: External Iterators in PHP Using OOP and External PHP Iterators using the ArrayIterator Class respectively.

It goes without saying that external iterators can be used for many different purposes, aside from those described above. What’s more, they can be utilized not only for traversing structures, but for lazy-loading data as well.

If you’re wondering how this can be achieved, I’ll be building a simple file helper class, which will be responsible for reading/writing data to a specified text file in the following sections. The “beauty” of this helper is that it will be able to lazy-load the data written to the pertaining file through the same array collection that you saw in the preceding tutorials.

Traversing Array Elements: Building a Custom Array Collection    

As stated in the introduction, the file helper that I plan to build in the following sections will use an external iterator to lazy-load the data saved to a given text file. In this particular case, I’ll be somewhat lazy too since the iterator employed by the helper in question will be the same custom array collection implemented in earlier chapters of this series.

In case that this collection doesn’t ring any bells to you, here it is again for your perusal:

(Utility/ArrayCollection.php)

<?php

namespace Utility;

class ArrayCollection implements \Countable, \Iterator, \ArrayAccess
{
    protected $_data = array();
   
    /**
     * Constructor
     */
    public function __construct(array $data = array())
    {
        if (!empty($data)) {
            $this->_data = $data;
        }
        $this->rewind();
    }
   
    /**
     * Count the number of elements in the collection (implementation required by Countable interface)
     */
    public function count()
    {
        return count($this->_data);
    }
   
    /**
     * Reset the collection (implementation required by Iterator interface)
     */    
    public function rewind()
    {
        reset($this->_data);
    }
   
    /**
     * Get the key of the current element in the collection (implementation required by Iterator interface)
     */
    public function key()
    {
        return key($this->_data);
    }
   
    /**
     * Get the current element in the collection (implementation required by Iterator interface)
     */
    public function current()
    {
        return current($this->_data);
    }

    /**
     * Check if there're more elements in the collection (implementation required by Iterator Interface)
     */
   
    public function valid()
    {
        return ($this->current() !== false);
    }
   
    /**
     * Move to the next element in the collection (implementation required by Iterator interface)
     */
    public function next()
    {
        next($this->_data);
    }
   
    /**
     * Add an element to the collection (implementation required by ArrayAccess interface)
     */
    public function offsetSet($key, $value)
    {
        if (!isset($key)) {
            $this->_data[] = $value;
        }
        else {
            $this->_data[$key] = $value;
        }
        return true;
    }
   
    /**
     * Remove an element from the collection (implementation required by ArrayAccess interface)
     */
    public function offsetUnset($key)
    {
        if (isset($this->_data[$key])) {
            unset($this->_data[$key]);
            return true;
        }
        return false;
    }
   
    /**
     * Get the specified element in the collection (implementation required by ArrayAccess interface)
     */
    public function offsetGet($key)
    {
        return isset($this->_data[$key]) ?
               $this->_data[$key] :
               null;
    } 
   
    /**
     * Check if the specified element exists in the collection (implementation required by ArrayAccess interface)
     */    
    public function offsetExists($key)
    {
        return isset($this->_data[$key]);
    }

    /**
     * Return the elements in the collection
     */
    public function toArray()
    {
        return $this->_data;
    }
}

Pretty simple right? As seen above, the “ArrayCollection” class is nothing but a simple wrapper for plain PHP arrays, which permits us to iterate over its elements, count them, and set/unset them as well.

In the following section I’ll be building the aforementioned file helper class, which will use the earlier array collection for lazy-loading the data written to a specific file.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

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: