Created
December 4, 2015 23:04
-
-
Save MartijnBraam/02fa6f6d122332ff5c62 to your computer and use it in GitHub Desktop.
Basic html element oop example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface renderable { | |
function render(); | |
} | |
abstract class Html implements renderable{ | |
protected $name; | |
protected $attributes = []; | |
protected $content; | |
public function render() { | |
$result = ''; | |
$result .= '<' . $this->name; | |
$attributes = []; | |
if (count($this->attributes)) { | |
$result .= ' '; | |
} | |
foreach ($this->attributes as $key => $value) { | |
$attributes[] = $key . '="' . $value . '"'; | |
} | |
$result .= join(' ', $attributes); | |
$result .= '>'; | |
if ($this->content !== NULL) { | |
$result .= $this->content . '</' . $this->name . '>'; | |
} | |
return $result; | |
} | |
} | |
class Text implements renderable{ | |
private $text; | |
function __construct($text) { | |
$this->text = $text; | |
} | |
function render() { | |
return $this->text; | |
} | |
} | |
abstract class HtmlContainer extends Html { | |
protected $children = []; | |
public function addChild(renderable $element) { | |
$this->children[] = $element; | |
} | |
public function render() { | |
$childHtml = []; | |
foreach ($this->children as $child) { | |
$childHtml[] = $child->render(); | |
} | |
$this->content = join('', $childHtml); | |
return parent::render(); | |
} | |
} | |
class Image extends Html { | |
function __construct($src) { | |
$this->name = 'img'; | |
$this->attributes['src'] = $src; | |
} | |
} | |
class Paragraph extends HtmlContainer { | |
function __construct() { | |
$this->name = 'p'; | |
} | |
} | |
class Div extends HtmlContainer { | |
function __construct() { | |
$this->name = 'div'; | |
} | |
} | |
class Heading extends Html { | |
function __construct($level, $text) { | |
$this->name = 'h' . $level; | |
$this->content = $text; | |
} | |
} | |
class Boek implements renderable{ | |
protected $name; | |
protected $image; | |
function __construct($name, $image) { | |
$this->name = $name; | |
$this->image = $image; | |
} | |
function render() { | |
$output = new Div(); | |
$output->addChild(new Heading(2, $this->name)); | |
$output->addChild(new Image($this->image)); | |
return $output->render(); | |
} | |
} | |
$boeken = new Div(); | |
$boeken->addChild(new Boek('De pizzamaffia', 'http://www.bruuttaal.nl/Jeugdliteratuur/Bronnen/Pizzamaffia.JPG')); | |
$boeken->addChild(new Boek('Javascript: The good parts', 'http://t0.gstatic.com/images?q=tbn:ANd9GcTRJVMsmtzmYn0U1Vrl_uI4X0Xbct7KvYhjeqEg7QxjBGn6fZx7')); | |
echo $boeken->render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment