Skip to content

Instantly share code, notes, and snippets.

@gooh
Created April 22, 2015 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooh/4b8f9eec685f0641834d to your computer and use it in GitHub Desktop.
Save gooh/4b8f9eec685f0641834d to your computer and use it in GitHub Desktop.
Universal Data Container
<?php
class DataCollection implements \IteratorAggregate
{
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function getIterator()
{
if (is_callable($this->data)) {
return new static(
call_user_func_array($this->data, func_get_args())
);
}
if (is_array($this->data)) {
return new \ArrayIterator($this->data);
}
if ($this->data instanceof \IteratorAggregate) {
return $this->data->getIterator();
}
if ($this->data instanceof \Iterator) {
return $this->data;
}
}
}
$array = new DataCollection([1,2,3,4,5]);
$callback = new DataCollection(function() { return [1,2,3,4,5]; });
$generator = new DataCollection(function() { for($i = 1; $i < 6; $i++) yield $i; });
print_r(iterator_to_array($array));
print_r(iterator_to_array($callback));
print_r(iterator_to_array($generator));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment