cs Composite

This commit is contained in:
Dominik Liebler
2013-09-11 16:10:36 +02:00
parent ed3bc7f2ec
commit 45ca69025b
4 changed files with 43 additions and 4 deletions

View File

@@ -3,7 +3,7 @@
namespace DesignPatterns\Composite;
/**
* composite pattern
* Composite pattern
*
* Purpose:
* to treat a group of objects the same way as a single instance of the object
@@ -18,7 +18,10 @@ namespace DesignPatterns\Composite;
*/
class Form extends FormElement
{
protected $_elements;
/**
* @var array|FormElement[]
*/
protected $elements;
/**
* runs through all elements and calls render() on them, then returns the complete representation
@@ -26,20 +29,26 @@ class Form extends FormElement
*
* from the outside, one will not see this and the form will act like a single object instance
*
* @param int $indent
*
* @return string
*/
public function render($indent = 0)
{
$formCode = '';
foreach ($this->_elements as $element) {
foreach ($this->elements as $element) {
$formCode .= $element->render($indent + 1) . PHP_EOL;
}
return $formCode;
}
/**
* @param FormElement $element
*/
public function addElement(FormElement $element)
{
$this->_elements[] = $element;
$this->elements[] = $element;
}
}

View File

@@ -2,7 +2,17 @@
namespace DesignPatterns\Composite;
/**
* Class FormElement
*/
abstract class FormElement
{
/**
* renders the elements' code
*
* @param int $indent
*
* @return mixed
*/
abstract public function render($indent = 0);
}

View File

@@ -2,8 +2,18 @@
namespace DesignPatterns\Composite;
/**
* Class InputElement
*/
class InputElement extends FormElement
{
/**
* renders the input element HTML
*
* @param int $indent
*
* @return mixed|string
*/
public function render($indent = 0)
{
return str_repeat(' ', $indent) . '<input type="text" />';

View File

@@ -2,8 +2,18 @@
namespace DesignPatterns\Composite;
/**
* Class TextElement
*/
class TextElement extends FormElement
{
/**
* renders the text element
*
* @param int $indent
*
* @return mixed|string
*/
public function render($indent = 0)
{
return str_repeat(' ', $indent) . 'this is a text element';