The Composite View design pattern offers users the versatility of handling single objects and collections through the same interface. But some programmers hesitate to use it due to its tricky implementation. Hesitate no longer; this multi-part series will take you step by step through some of the best ways to use the Composite View design pattern, complete with code samples to show you the way.
As the old proverb says, a long walk always begins with a single step. In keeping with this idea, the first thing I’m going to do to implement the Composite View pattern will be to build an abstract parent class. This class will encapsulate the functionality and structure of generic view objects. Later on, refined implementations of this parent will be responsible for handling one and multiple view objects through the same interface.
With that said, here’s how this abstract parent looks in its initial stage:
// constructor public function __construct($template = '', array $data = array()) { if ($template !== '') { $this->setTemplate($template); } if (!empty($data)) { foreach ($data as $name => $value) { $this->$name = $value; } } }
// set a new view template public function setTemplate($template) { $template = $template . '.php'; if (!file_exists($template)) { throw new ViewException('The specified view template does not exist.'); } $this->_template = $template; }
// get the view template public function getTemplate() { return $this->_template; }
// set a new property for the view public function __set($name, $value) { $this->_properties[$name] = $value; }
// get the specified property from the view public function __get($name) { if (!isset($this->_properties[$name])) { throw new ViewException('The requested property is not valid for this view.'); } return $this->_properties[$name]; }
// remove the specified property from the view public function __unset($name) { if (isset($this->_properties[$name])) { unset($this->_properties[$name]); } } }
(ViewException.php)
<?php
class ViewException extends Exception{}
As you can see, the above “AbstractView” class is quite easy to follow. It simply implements the magic “__set()” and “__get()” PHP methods to add and fetch undeclared view properties dynamically, which are stored in a protected array for further processing. The class also defines a mutator and an accessor for its “$_template” property, which can be used for handling the template file that the view class is going to render.
While this abstract parent is currently pretty functional, it still isn’t capable of manipulating single and multiple views via the same interface, in accordance with the commandments imposed by the Composite pattern. So it’s time to provide the class with this ability. We'll achieve this by defining a couple of abstract methods.
The signatures of these methods will be shown in the following segment, so click on the link below and keep reading.