Skip to content

Instantly share code, notes, and snippets.

@arleighdickerson
Created August 11, 2016 04:04
Show Gist options
  • Save arleighdickerson/f3117611f2e7e1bca48a4e2a3e36ecea to your computer and use it in GitHub Desktop.
Save arleighdickerson/f3117611f2e7e1bca48a4e2a3e36ecea to your computer and use it in GitHub Desktop.
Autoload theme-specific controllers
<?php
namespace frontend\components;
use Yii;
/**
* Class ThemeAutoloader
*
* @package frontend\components
* @author Arleigh Dickerson
*/
class ThemeAutoloader {
private $_themeName;
private $_namespace;
private $_themeDir;
private function __construct($themeName, $namespace, $themeDir) {
$this->_themeName = $themeName;
$this->_namespace = ltrim($namespace, '\\');
$this->_themeDir = Yii::getAlias($themeDir);
}
public function __invoke($className) {
if (!$this->startsWith($className, $this->_namespace)) {
return;
}
$themePath = $this->_themeDir . "/" . $this->_themeName;
$classPath = substr(ltrim(str_replace('\\', '/', $className), '/'), strlen($this->_namespace . '\\'));
$classFile = Yii::getAlias($themePath . '/' . $classPath . '.php', false);
if ($classFile === false || !is_file($classFile)) {
return;
}
include($classFile);
}
/**
* Call this in bootstrap
*
* @param string $themeName
* @param string $namespace
* @param string $themeDir
*/
public static function register($themeName, $namespace = null, $themeDir = null) {
if ($namespace === null) {
$namespace = basename(dirname(__DIR__));
}
if ($themeDir === null) {
$themeDir = dirname(__DIR__) . '/themes';
}
spl_autoload_register(new static($themeName, $namespace, $themeDir), true, true);
}
private static function startsWith($str, $with) {
return substr($str, 0, strlen($with)) == $with;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment