Home arrow PHP arrow Page 3 - Segregated Interfaces in PHP

Implementing the ArrayAccess Interface - PHP

In this first part of a programming series, you will learn how to create segregated interfaces to perform specific tasks in PHP. In this instance, you will be using them to iterate through arrays.

TABLE OF CONTENTS:
  1. Segregated Interfaces in PHP
  2. Building an Array Collection in PHP
  3. Implementing the ArrayAccess Interface
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
June 15, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


Giving the final touches to the collection: implementing the “ArrayAccess” interface

As noted in the preceding segment, the last step that must be taken to get the earlier array collection up and running is to make it an implementer of another segregated interface - in this case the built-in “ArrayAccess”. Even when this process has nothing specially difficult, below I included the finished code of the collection, so that you can study it in depth. Here it is: 

(ArrayCollection.php)<?phpclass 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 ($key === null) {
            if (!in_array($key, $this->_data, true)) {
                $this->_data[] = $value;
                return true;
            }
        }
        else if (!array_key_exists($key, $this->_data)) {
            $this->_data[$key] = $value;
            return true;
        }
        return false;
    }
   
    /**
     * Remove an element from the collection (implementation required by ArrayAccess interface)
     */
    public function offsetUnset($key)
    {
        if (array_key_exists($key, $this->_data)) {
            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 array_key_exists($key, $this->_data) ?
               $this->_data[$key] :
               null;
    } 
   
    /**
     * Check if the specified element exists in the collection (implementation required by ArrayAccess interface)
     */    
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->_data);
    }
}

If you thought that segregated interfaces were a hard-to-grasp concept, the above example should make you change your mind. Although it’s quite probable that you’ve already created a custom array collection similar to the one above, you should think of it as a class which uses three different segregated interfaces in order to implement only the functionality that it needs to get its job done.

In addition, here’s a short script that shows how to use the pertaining collection for iterating over a trivial array and counting its elements as well. Look at it, please:

<?php// include the collection
require_once 'ArrayCollection.php';// create a range of values
$data = range(1, 20);// add the range to the collection
$collection = new ArrayCollection($data);// iterate over the collection
echo 'Elements in the collection: <br />';
foreach ($collection as $key => $value) {
    echo 'Key: ' . $key . ' Value: ' . $value . '<br />';
}// count the number of elements in the collection
 echo 'Number of elements in the collection: ' . count($collection);/*
displays the followingElements in the collection:
Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 3
Key: 3 Value: 4
Key: 4 Value: 5
Key: 5 Value: 6
Key: 6 Value: 7
Key: 7 Value: 8
Key: 8 Value: 9
Key: 9 Value: 10
Key: 10 Value: 11
Key: 11 Value: 12
Key: 12 Value: 13
Key: 13 Value: 14
Key: 14 Value: 15
Key: 15 Value: 16
Key: 16 Value: 17
Key: 17 Value: 18
Key: 18 Value: 19
Key: 19 Value: 20
Number of elements in the collection: 20*/

Undeniably, the above example speaks for itself, meaning that you shouldn’t have major troubles using it as a starting point for defining your own segregated interfaces. But, still don’t have a clue on how to use a segregated interface in other uses cases, other than when building array collections?

Well, don’t worry and feel free to offload this task to me. And I’m saying this because in the following tutorial I’m going to demonstrate how to utilize a segregated interface in the construction of a dynamic registry. Meanwhile, stop by the article’s final thoughts.

Final thoughts

In this first installment of the series, I provided you with an introduction to using segregated interfaces in PHP. Moreover, through a fairly simple example, I demonstrated what they are and how useful they can be when it comes to provide their eventual implementers with the functionality that they require to perform specific tasks.

In the coming part, things will become even more interesting, as I’m going to show you how to utilize a segregated interface in the development of an extendable registry system.

As usual, don’t miss the next post! 



 
 
>>> 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: