Skip to content

Instantly share code, notes, and snippets.

@jm42
Created October 19, 2014 02:46
Show Gist options
  • Save jm42/0bafdc8792c90bdec3a7 to your computer and use it in GitHub Desktop.
Save jm42/0bafdc8792c90bdec3a7 to your computer and use it in GitHub Desktop.
Basic Loader Interface with Delegate Lookup
<?php
interface LoaderInterface {
function load($resource);
function supports($resource);
}
abstract class Loader implements LoaderInterface {
private $delegate;
private $loading = [];
public function __construct(LoaderInterface $delegate=null) {
if ($delegate === null) {
$delegate = $this;
}
$this->delegate = $delegate;
}
protected function import($resource) {
if (isset($this->loading[$resource])) {
throw new RuntimeException("Cyclic reference for $resource");
}
$this->loading[$resource] = true;
$result = $this->delegate->load($resource);
unset($this->loading[$resource]);
return $result;
}
}
class LoaderComposite implements LoaderInterface {
private $loaders;
public function __construct(array $loaders=[]) {
foreach ($loaders as $loader) {
$this->addLoader($loader);
}
}
public function addLoader(LoaderInterface $loader) {
$this->loaders[] = $loader;
}
public function load($resource) {
foreach ($this->loaders as $loader) {
if ($loader->supports($resource)) {
return $loader->load($resource);
}
}
throw new RuntimeException(
"Resource $resource has no registered loader"
);
}
function supports($resource) {
foreach ($this->loaders as $loader) {
if ($loader->supports($resource)) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment