Using an Iterator Interface to Create “Round-Robin” Array

I had a requirement that seemed to need a way to cycle through a set of values in an array in such a way that when I got to the end of the array, it would start over at the beginning, essentially load-balancing the use of those array elements. Perhaps you might want to do the same thing for a set of ads, making sure a given user sees each available advertisement before starting again with the first (perhaps an array stored in $_SESSION?).

After exploring a few alternatives, one I found that I kind of like (for its elegance if not its lack of brevity) was to use PHP’s built-in Iterator interface. The concept here was to load any array into an instance of a class that implements the Iterator, and then simply using the Iterator::next() method to get the current value, then advance the array pointer, pointing it back to the beginning if it has reached the end of the array. Without further ado, the class:


<?php

class RoundRobin implements Iterator
{
    private 
$var = array();

    public function 
__construct($array)
    {
        if (
is_array($array)) {
            
$this->var $array;
        }
    }

    public function 
rewind()
    {
        
reset($this->var);
    }

    public function 
current()
    {
        return 
current($this->var);
    }

    public function 
key()
    {
        return 
key($this->var);
    }

    
/**
     * Get the current array element, then advance the pointer
     * @return mixed
     */
    
public function next()
    {
        
$var current($this->var);
        
next($this->var);
        if(!
$this->valid()) {
            
$this->rewind();
        }
        return 
$var;
    }

    public function 
valid()
    {
        
$key key($this->var);
        return (
$key !== NULL && $key !== FALSE);
    }
}

A sample usage:


<?php

$data 
= new RoundRobin(range(1,10));
$dbStuff getLotsOfStuffFromTheDB();
foreach(
$dbStuff as $stuff) {
    
$result getSomeMoreStuff($dbStuff['foo'], $data->next());
}

Danger, Will Robinson. Don’t do this, or you’ll have an endless loop:


<?php

$data 
= new RoundRobin(range(1,10));
foreach(
$data as $foo) {
    echo 
$foo "<br />\n";
}

Review: PHP 5 Social Networking

PHP 5 Social Networking by Michael Peacock (Packt Publishing) is a book that takes you through the process of creating a social networking web site written in PHP (preferably at least PHP 5.2.0). It is probably not ideal for beginners just getting into web programming, but if you have at least a little bit of experience it could be a good way to get your feet wet while actually creating some useful code.

The book essentially walks you through the creation of a sample site. You’ll see many of the features you’re familiar with in sites such as FaceBook, if somewhat stripped down without many of the bells and whistles. The author discusses some of the choices and viable alternatives to consider at each point of the process, including deciding how much code to create yourself versus some of the ready-made third-party alternatives to look at (view full table of contents).

If you download the code from the PacktPub.com web site, along with this book you will then essentially have a working framework for a social networking site with full, detailed documentation. While this may be exactly what you need, for my level of ability plus my particular interests at this time, I probably would have been more interested in something that dealt more with the design-level considerations: more class diagrams and discussions of “why” as opposed to specific source code and explanations of “how”. (As a bit of an aside: as far as I can tell, there is only one class in the code base which is ever extended, and there is no use of interfaces or abstract classes. This is not necessarily bad, as they may not always be necessary, but I would think for a project of this size there would have been more inheritance and such in a decent object-oriented design.)

E-book versions in PDF or ePUB formats are available from the publisher. It is not currently available from Amazon.com in a Kindle version (nor do I know if it ever will be), but I was able to convert the ePUB document to MOBI via the Calibre program and view it on my Kindle, though ultimately I find it easier to read such technical books in the paper version.

All in all this seems to be a solid product, perhaps not exactly the sort of thing I might look for, but definitely worth your considertaion if you are thinking about diving into the world of social networking web sites.

Book Review: CodeIgniter 1.7 Professional Development

I was recently provided a review copy of CodeIgniter 1.7 Professional Development by Adam Griffith (Packt Publishing). It claims that it will help the reader “Become a CodeIgniter expert with professional tools, techniques and extended libraries.” As someone who has used CodeIgniter and found it to be very useful, I was looking forward to learning more and becoming a CI power user. However, I cannot say that my wish was fulfilled.

While some of the second half of the book introduced me to a few CI features I did not know about or at least had not yet used, most of the book was either about things I already knew or things I didn’t really care much about.

Most of the first half of the book essentially reiterated things you can find in the CI documentation, and that documentation is one of the strong points of CI. Also, some of the organization of the material was odd, such as detailing the image manipulation library before discussing a basic functionality such as session data handling. Some of the code samples seemed to be less than optimal as good examples of object-oriented PHP, such as the large switch/case block in the “Rest” class in Chapter 8.

My overall response to this book is therefore that it might be of use to intermediate-level PHP users who are new to CodeIgniter (with the caveat that it is not necessarily a good source for learning good OOP practices), but the experienced CodeIgniter user probably will find little in this book to make it worth purchasing. I’d probably only give it 2-1/2 stars out of 5.

Object Iteration in PHP 5

PHP 5 gives us the ability to iterate through objects much as we can with arrays, such as with the foreach() loop construct. I knew this ability existed but had not really looked into it or made use of it. However as a result of a thread at PHPBuilder.com, I thought this might be a good solution.

The key here is that while the default behavior of object iteration is to access each of the object’s public properties, you can override that behavior via the Iterator interface, defining custom methods to iterate what you specifically want from the object.

Continue reading “Object Iteration in PHP 5”

Beginners’ Corner: Learning Object-Oriented PHP

I often see PHP newbies (and even not-so-newbies) who are confused by the world of object-oriented programming (OOP). At least part of this confusion results from the vast majority of introductory books and tutorials for PHP beginning by teaching procedural programming techniques, treating OOP as an “advanced” subject with a chapter or two at the end. Thus the student is exposed to a bunch of new syntax concerning classes and objects with, at best, a very brief explanation as to “why” that syntax should be used. A purely object-oriented language such as Java or Ruby, on the other hand, will by its nature require that beginners’ resources more fully address the theory of OOP.

I am not going to claim to be an OOP guru, but I can point you to a few resources I have used to become reasonably proficient — but still learning! — with PHP classes and objects. First I would point you to an on-line tutorial at Sun.com: “Lesson: Object-Oriented Programming Concepts“. While the (relatively few) examples in these tutorials are in Java, the syntax is quite similar to that of PHP, and the lessons they illustrate are easily transferred to PHP. If you want to work with those examples yourself in PHP, I would recommend taking a look at a couple PHP tutorials at IBM.com: “Getting started with objects in PHP V5” and “Advanced PHP V5 objects“.

Once you’ve gotten past the basics, to see how things can work together as an OOP whole, I strongly suggest you get your hands on Matt Zandstra’s book, PHP Objects, Patterns, and Practice. Reading this book is what ultimately made objects “click” in my mind. After reading it I felt much more comfortable with the underlying concepts along with the specific techniques for applying them in my PHP projects.

Implementing a Database-based Session-handler

While I’ve been using the database session data handler in the CodeIgniter framework for some time, upon reading this thread at PHPBuilder forums I decided it was time to write my own. In part I just wanted to gain a more thorough understanding of the process, and I also figured I could use it some day for a small project that does not require the power of CodeIgniter or something similar.

I decided to use an OOP approach for this, creating two classes. One class, SessionHandler, would be the interface the client code will use to establish the session-handler functions. A second class, SessionData, would handle the actual interface with the database. For now it uses the MySQLi database
interface; but if I wanted to use PDO or something else, I would just need to either edit the SessionData class appropriately, or even go to some sort of abstract factory pattern, perhaps, to instantiate a DBMS-specific class. For now, though, I’ll just keep it “simple” with only the MySQLi class.

Continue reading “Implementing a Database-based Session-handler”