As of PHP 7.1, you can now type hint your method/function arguments with the keyword iterable for handling arrays or even objects that implement the Traversable interface.
Let’s create an example where we can convert any string to a slug. We’ll have 2 methods so that we can pass either a string or iterable data.
We’ll start by setting up our SlugGenerator class.
<?php
class SlugGenerator
{
public static function byArray(iterable $data)
{
$results = [];
foreach($data as $name) {
$results[] = self::byString($name);
}
return $results;
}
public static function byString(string $name)
{
$slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $name);
$slug = strtolower($slug);
return $slug;
}
}
For our first example on using the above we’ll use a simple array.
<?php
$titles = [
'My Test Title 1',
'My Test Title 2',
'My Test Title 3',
];
$slugs = SlugGenerator::byArray($titles); // Outputs array of slugs
Now let’s setup an example by passing a traversable object.
<?php
class Titles implements IteratorAggregate
{
private $titles = [];
public function add(string $title)
{
array_push($this->titles, $title);
}
public function getIterator()
{
return new ArrayIterator($this->titles);
}
}
$titles = new Titles;
$titles->add('Test Title 1');
$titles->add('Test Title 2');
$titles->add('Test Title 3');
$slugs = SlugGenerator::byArray($titles); // Outputs array of slugs
You'll see that we’re able to use the same SlugGenerator class without having to modify our original class. Awesome, right?