Skip to content

Instantly share code, notes, and snippets.

@rizqidjamaluddin
Created October 16, 2015 12:18
Show Gist options
  • Save rizqidjamaluddin/737b7e59cd470ec872d1 to your computer and use it in GitHub Desktop.
Save rizqidjamaluddin/737b7e59cd470ec872d1 to your computer and use it in GitHub Desktop.
<?php
// the classes
abstract class File {
// visitor pattern
function accept (TreeRenderer $renderer) {
$renderer->render($this);
}
}
class Folder extends File {
public $files = [];
public $name = "Folder";
}
class Image extends File {
public $url = "foo.jpg";
}
<?php
// the renderers - uses
class TreeRenderer {
public function render (File $file) {
// we'll use string concats, but you could also use a node tree and transform to XML
$result = "";
if ($file instanceof Folder) {
$result .= "<li>";
$result .= e($file->name);
$result .= "<ul>";
// fun fact - using the visitor pattern we could loop through children in Folder::accept,
// but we can't because we needed to render folders _around_ the files, not just before/after
foreach ($file->files as $subFile) {
$result .= $this->render($subFile);
}
$result .= "</ul></li>";
} elseif ($file instanceof Image) {
$result .= "<li>";
$result .= '<img src="'.url($file->url).'" />'
$result .= "</li>";
}
}
}
<?php
// usage example - you can do this wherever
class TreeRendererHelper {
public function draw ($file) {
$renderer = new TreeRenderer;
$html = $renderer->render($file);
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment