Skip to content

Instantly share code, notes, and snippets.

@kandran
Last active August 29, 2015 14:18
Show Gist options
  • Save kandran/32e0e8d7a738616002be to your computer and use it in GitHub Desktop.
Save kandran/32e0e8d7a738616002be to your computer and use it in GitHub Desktop.
Design pattern Visiteur en php (http://kandran.fr/design-pattern-visiteur)
<?php
require_once('Document.php');
class ConfigDocument extends Document
{
}
<?php
require_once('IDocumentRenderer.php');
class Document
{
protected $data = array();
public function setData(array $data)
{
$this->data = $data;
}
public function accept(IDocumentRenderer $renderer)
{
$renderer->visit($this);
}
public function getData()
{
return $this->data;
}
}
<?php
require_once('IDocumentRenderer.php');
abstract class DocumentRenderer implements IDocumentRenderer
{
protected $output;
public function getOutput()
{
return $this->output;
}
}
<?php
require_once('DocumentRenderer.php');
class HtmlRenderer extends DocumentRenderer
{
public function visit(Document $document)
{
$data = $document->getData();
$this->output = "<table>";
foreach ($data as $key => $value) {
$this->output .= "<tr><td>$key</td><td>$value</td></tr>";
}
$this->output .= "<table>";
}
}
<?php
require_once('Document.php');
interface IDocumentRenderer
{
public function visit(Document $document);
}
<?php
require_once('DocumentRenderer.php');
class TextRenderer extends DocumentRenderer
{
public function visit(Document $document)
{
$data = $document->getData();
$this->output = "";
foreach ($data as $key => $value) {
$this->output .= "$key:$value\n";
}
}
}
<?php
require_once('ConfigDocument.php');
require_once('HtmlRenderer.php');
require_once('TextRenderer.php');
require_once('XMLRenderer.php');
function render($doc, $renderer)
{
$doc->accept($renderer);
return htmlentities($renderer->getOutput());
}
$doc = new ConfigDocument();
$doc->setData(array(
"key1" => "value1",
"key2" => 5
));
$htmlRenderer = new HtmlRenderer();
echo "<br/><br/>html <br/>" . render($doc, $htmlRenderer);
$textRenderer = new TextRenderer();
echo "<br/><br/>text <br/>" . render($doc, $textRenderer);
$xmlRenderer = new XmlRenderer();
echo "<br/><br/>xml <br/>" . render($doc, $xmlRenderer);
<?php
require_once('DocumentRenderer.php');
class XmlRenderer extends DocumentRenderer
{
public function visit(Document $document)
{
$data = $document->getData();
$this->output = "<items>";
foreach ($data as $key => $value) {
$this->output .= "<item key='$key'>$value</item>";
}
$this->output .= "<items>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment