Skip to content
lasso edited this page Nov 30, 2016 · 4 revisions

What is an Enumerable?

An enumerable is an "collection like" object that can be traversed using a specific method call. Each time the method is called, the Enumerable object will return the "next" element in the collection until the collection runs out of elements.

The primary inspiration for this implementation of Enumerables comes from the programming language ruby, which uses them extensively for collections like arrays and dictionaries.

Even though PHP and ruby works differently it is quite easy to implement Enumerables in PHP. These are the basic facts you need to know in order to make use of Enumerables using this library.

Use the Enumerable trait

Any class can be an Enumerable. The first thing you need to do is to use the Enumerable trait.

use Lasso3000\Enumerable;

class MyEnumerable {
    use Enumerable;

    // ...rest of class definition goes here
}

Implement the __each method

The Enumerable trait contains an abstract method, __each, which needs to be implemented. This method will tell the Enumerable trait how you want to traverse your collection. It it also a generator function, meaning that it should yield values rather than return them. The order of the yielded elements also represent the order in which your object will be traversed, meaning you can change the traversal order by just changing your implementation of __each.

use Lasso3000\Enumerable;

class MyEnumerable {
    use Enumerable;

    protected function __each()
    {
        yield 'FIRST';
        yield 'SECOND';
        yield 'THIRD';
    }

    // ...rest of class definition goes here
}

Please note that you can yield anything. You are not limited to simple data types, you may return arbitrary complex objects. The Enumerable trait will work with any yielded value.

The EnumerableArray class

Some Enumerable methods will return a "list" of items. In order to make this "list" an Enumerable (so that you can chain method calls) the list will be an instance of the EnumerableArray class. The EnumerableArray is a simple wrapper around an ordinary array, but since it uses the Enumerable trait you can call more Enumerable methods on it. For instance:

$myEnum = new MyEnumerable();

$myEnum->map('strtolower')
    ->map('strrev')
    ->each(function($elem) { echo "{$elem}\n"; });

// will print
// tsrif
// dnoces
// driht
// on the console

To get the underlying array, you can call EnumerableArray#toArray. That method will return an ordinary array, not an object.

That's actually everything you need to set up yourself, the Enumerable trait will now magically give your object the power of a "real" collection object. In order to se what you can do with an Enumerable object, please have a look at the code samples.

Clone this wiki locally