mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-04 05:57:25 +02:00
cs Composite
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
@@ -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);
|
||||
}
|
||||
|
@@ -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" />';
|
||||
|
@@ -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';
|
||||
|
Reference in New Issue
Block a user