Created
October 19, 2014 02:46
-
-
Save jm42/0bafdc8792c90bdec3a7 to your computer and use it in GitHub Desktop.
Basic Loader Interface with Delegate Lookup
This file contains hidden or 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 | |
| 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