Skip to content

Instantly share code, notes, and snippets.

@simics-ja
Last active December 6, 2021 05:44
Show Gist options
  • Save simics-ja/6f3658a819772f2399920647edc86199 to your computer and use it in GitHub Desktop.
Save simics-ja/6f3658a819772f2399920647edc86199 to your computer and use it in GitHub Desktop.
[PHPデザインパターン] 参考サイト:https://www.ritolab.com/category/PHP/DesignPatterns #php #design

Iterator

アンチパターン

以下のようなクラスからUserList取得してforeachで回すパターンは、Userのフィールドを増やそうとしたときに、メソッドの追加やテストが必要になったりする。 大規模なコードを変更するときには、この実装では変更箇所やテストが多く発生するため、これを最初に抑えるデザインパターンがIteratorパターンである。

class User
{
    protected $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

class Roster
{
    protected $userList = [];

    public function setUserList($user)
    {
        $this->userList[] = $user;
    }

    public function getUserList()
    {
        return $this->userList;
    }

}
interface UsersAggregateInterface {
public function createIterator();
}
interface UserListIteratorInterface {
public function hasNext();
public function next();
}
class UserListIterator implements UserListIteratorInterface {
private $users;
private $position = 0;
function __construct($users)
{
$this->users = $users;
}
public function hasNext()
{
return isset($this->users[$this->position]);
}
public function next()
{
return $this->users[$this->position++];
}
}
class UsersAggregate implements UsersAggregateInterface {
private $userList;
function __construct($users)
{
$this->userList = $users;
}
public function addUsersList($user)
{
$this->userList[] = $user;
}
public function getUserList()
{
return $this->userList;
}
public function createIterator()
{
return new UserListIterator($this->userList);
}
}
class RosterClient {
private $userIterator;
function __construct(UsersAggregateInterface $user_list)
{
$this->userIterator = $user_list->createIterator();
}
function getUsers()
{
while ($this->userIterator->hasNext()) {
$user = $this->userIterator->next();
echo sprintf("%s", $user);
echo "<br>";
}
}
}
$users = [ "name 01", "name 02", "name 03", "name 04", "name 05" ];
$list = new RosterClient(new UsersAggregate($users));
echo $list->getUsers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment