Last active
April 26, 2017 20:54
-
-
Save rgomezcasas/5ee2dd520762c5acd53c622e40459d67 to your computer and use it in GitHub Desktop.
Example of collection in php. More: http://codely.tv/screencasts/finder-kata-php-colecciones-funcional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// User.php | |
final class User | |
{ | |
private $birthYear; | |
public function __construct(int $birthYear) | |
{ | |
$this->birthYear = $birthYear; | |
} | |
public function birthYear(): int | |
{ | |
return $this->birthYear; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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