Skip to content

Instantly share code, notes, and snippets.

@rmruano
Created September 10, 2014 18:28
Show Gist options
  • Select an option

  • Save rmruano/6b44bbeb62e861e32a9f to your computer and use it in GitHub Desktop.

Select an option

Save rmruano/6b44bbeb62e861e32a9f to your computer and use it in GitHub Desktop.
Just a very simple demo showing how to get a filtered subset from a collection by using generators.
<?php
/**
* PHP 5.5+ Required
* How to get a filtered subset from a collection by using generators.
* @author http://www.github.com/rmruano
*/
/* 1. Classes definition ------------------------------------------------------------------------ */
class MyUser {
/**
* @var string
*/
private $name;
/**
* @var $age
*/
private $age;
/**
* @param string $name
* @param int|null $age
*/
public function __construct($name, $age = null) {
$this->name = $name;
$this->age = $age;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @return int|null
*/
public function getAge() {
return $this->age;
}
}
class MyGroup {
/**
* @var MyUser[]
*/
private $objects;
/**
* @param MyUser $user
* @return $this
*/
public function add(MyUser $user) {
$this->objects[] = $user;
return $this;
}
/**
* Get objects matching the filter
* @see http://php.net/manual/en/language.generators.overview.php
* @param int $minAge
* @param int $maxAge
* @return MyUser[]
*/
public function ageRange($minAge=0, $maxAge=PHP_INT_MAX) {
foreach ($this->objects as $user) {
$age = $user->getAge();
if ($age!=null && $age>=$minAge && $age<=$maxAge) {
yield $user;
}
}
}
}
/* 2. Demo usage ------------------------------------------------------------------------ */
$myGroup = (new MyGroup())
->add(new MyUser("David",35))
->add(new MyUser("Phil",20))
->add(new MyUser("Bruce",39));
foreach($myGroup->ageRange(30,40) as $myObject) {
echo $myObject->getName() . " (Age ".$myObject->getAge().")".PHP_EOL;
}
/*
EXPECTED OUTPUT:
David (Age 35)
Bruce (Age 39)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment