Skip to content

Instantly share code, notes, and snippets.

@rgomezcasas
Last active April 26, 2017 20:54
Show Gist options
  • Save rgomezcasas/5ee2dd520762c5acd53c622e40459d67 to your computer and use it in GitHub Desktop.
Save rgomezcasas/5ee2dd520762c5acd53c622e40459d67 to your computer and use it in GitHub Desktop.
<?php
// We want to find all users born after 1950
$users = [new User(1994), new User(2000), new User(1900), new User(25)];
$usersBornedAfter1950 = [];
foreach ($users as $user) {
if ($user->birthYear() > 1950) {
$usersBornedAfter1950[] = $user;
}
}
var_dump($usersBornedAfter1950); // [User(1900), User(25)]
<?php
// User.php
final class User
{
private $birthYear;
public function __construct(int $birthYear)
{
$this->birthYear = $birthYear;
}
public function birthYear(): int
{
return $this->birthYear;
}
}
<?php
use function Lambdish\Phunctional\filter;
final class Users
{
private $users;
public function __construct(User ...$users)
{
$this->users = $users;
}
public function bornAfter(int $year): Users
{
return new self(filter($this->hasBornAfter($year), $this->users));
}
private function hasBornAfter(int $year)
{
return function (User $user) use ($year) {
return $user->birthYear() > $year;
};
}
}
<?php
final class Users
{
private $users;
public function __construct(User ...$users)
{
$this->users = $users;
}
public function bornAfter(int $year): Users
{
$usersBornedAfterYear = [];
foreach ($this->users as $user) {
if ($user->birthYear() > $year) {
$usersBornedAfterYear[] = $user;
}
}
return new self($usersBornedAfterYear);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment