Composite(コンポジット・パターン)を使うと木構造のような再帰的なパターンを表現することができる。
■コード
Component.php
abstract class Component { abstract public function add(Component $branch); }
Branch.php
枝のクラス。
class Branch extends Component { private $_children; public function __construct() { $this->_children = array(); } public function add(Component $branch) { return array_push($this->_children, $branch); } }
Leaf.php
葉っぱ。
class Leaf extends Component { public function add(Component $branch) { throw new Exception('leaves cannot have any leaves'); } }
■クライアントコード
$branch = new Branch(); $branch->add(new Leaf()); $branch->add(new Leaf()); $branch->add(new Leaf()); var_dump($branch); /* object(Branch)[1] private '_children' => array 0 => object(Leaf)[2] 1 => object(Leaf)[3] 2 => object(Leaf)[4] */