Skip to content

Instantly share code, notes, and snippets.

@bobthecow
Created November 16, 2010 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobthecow/701275 to your computer and use it in GitHub Desktop.
Save bobthecow/701275 to your computer and use it in GitHub Desktop.
<?php
class PartialsLoader implements ArrayAccess {
protected $baseDir;
protected $extensions = array('mustache', 'stache', 'ms');
protected $partials = array();
public function __construct($baseDir = null) {
$this->baseDir = (isset($baseDir)) ? $baseDir : dirname(__FILE__);
}
public function offsetExists($offset) {
return ($this->findPartial($offset) !== null);
}
public function offsetSet($offset, $value) {
throw new InvalidArgumentException('PartialsLoader is read-only o_O');
}
public function offsetUnset($offset) {
throw new InvalidArgumentException('PartialsLoader is read-only o_O');
}
public function offsetGet($offset) {
if (!isset($this->partials[$offset])) {
$this->partials[$offset] = $this->loadPartial($offset);
}
return $this->partials[$offset];
}
protected function findPartial($name) {
foreach ($this->extensions as $ext) {
$filename = sprintf("%s/%s.%s", $this->baseDir, $name, $ext);
if (file_exists($filename)) {
return $filename;
}
}
}
protected function loadPartial($name) {
$filename = $this->findPartial($name);
if ($filename === null) {
throw new UnknownPartialExtension(sprintf(
'Partial template %s does not exist in %s', $offset, $this->baseDir
));
}
return file_get_contents($filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment