Created
October 16, 2015 12:18
-
-
Save rizqidjamaluddin/737b7e59cd470ec872d1 to your computer and use it in GitHub Desktop.
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 | |
// 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"; | |
} |
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 | |
// 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>"; | |
} | |
} | |
} |
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 | |
// 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