Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- final class HtmlBuilder {
- private $_elements = array();
- public function addElement(HtmlElement $element) {
- if ($element == null)
- return;
- $this->_elements[] = $element;
- }
- public function render() {
- foreach ($this->_elements as $element) {
- echo $element->render();
- }
- }
- }
- abstract class HtmlElement {
- protected $commonAttributes = array("id", "class", "title");
- protected $customAttributes = array();
- protected $attributes;
- protected $output;
- protected function __construct() {
- $this->attributes = new AttributeCollection();
- $this->output = "";
- }
- public function setAttribute(Attribute $attribute) {
- if ($this->isValidAttribute($attribute->name)) {
- $this->attributes->addAttribute($attribute);
- }
- }
- protected function isValidAttribute($name) {
- if (in_array($name, $this->commonAttributes) || in_array($name, $this->customAttributes))
- return true;
- return false;
- }
- public abstract function render();
- }
- final class Attribute {
- public $name;
- public $value;
- public function __construct($name, $value) {
- $this->name = $name;
- $this->value = $value;
- }
- }
- final class AttributeCollection {
- private $_attributes = array();
- public function addAttribute(Attribute $attribute) {
- if ($attribute == null)
- return;
- $this->_attributes[] = $attribute;
- }
- public function attributeExists($name) {
- foreach ($this->_attributes as $attribute) {
- if ($attribute->name == $name)
- return true;
- }
- return false;
- }
- public function getValue($name) {
- if ($this->attributeExists($name)) {
- foreach ($this->_attributes as $attribute) {
- if ($attribute->name == $name) {
- return $attribute->value;
- }
- }
- }
- }
- public function getAttributes() {
- return $this->_attributes;
- }
- }
- final class Image extends HtmlElement {
- public function __construct() {
- parent::__construct();
- $this->customAttributes = array("src", "alt", "height", "width");
- }
- public function render() {
- $this->output .= "<img";
- foreach ($this->attributes->getAttributes() as $attribute) {
- $this->output .= ' ' . $attribute->name . '="' . $attribute->value . '"';
- }
- $this->output .= ' />';
- return $this->output;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement