@brandy
The Composite design pattern is a structural design pattern that allows you to treat individual objects and compositions of objects uniformly. This is done by creating an abstract class that represents both individual objects and collections of objects. Objects that represent collections have the ability to contain further objects of the same kind.
In PHP, you can use the Composite design pattern to represent tree-like structures using the following steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
abstract class Component { protected $name; function __construct($name) { $this->name = $name; } abstract function add(Component $c); abstract function remove(Component $c); abstract function get($index); abstract function doSomething(); } |
1 2 3 4 5 6 7 8 |
class Leaf extends Component { function add(Component $c) {} function remove(Component $c) {} function get($index) {} function doSomething() { echo $this->name . " has done something.<br/>"; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Composite extends Component { private $children = array(); function add(Component $c) { array_push($this->children, $c); } function remove(Component $c) { $key = array_search($c, $this->children, true); if ($key !== false) { unset($this->children[$key]); } } function get($index) { return $this->children[$index]; } function doSomething() { echo $this->name . " has done something.<br/>"; foreach ($this->children as $child) { $child->doSomething(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$root = new Composite("Root"); $branch1 = new Composite("Branch 1"); $branch2 = new Composite("Branch 2"); $leaf1 = new Leaf("Leaf 1"); $leaf2 = new Leaf("Leaf 2"); $leaf3 = new Leaf("Leaf 3"); $root->add($branch1); $root->add($branch2); $branch1->add($leaf1); $branch2->add($leaf2); $branch2->add($leaf3); $root->doSomething(); |
The result will be a tree-like structure where the Root object contains two branches, each containing one or two leaves. When the doSomething() method is invoked on the Root object, the action will be performed on all components in the structure.