Merge pull request #305 from hcpss-banderson/feature/avoid-multuple-autoloaders

Prevent redundant autoloader registerations. Fixes #304
This commit is contained in:
Justin Hileman
2017-01-05 00:32:42 -08:00
committed by GitHub
2 changed files with 32 additions and 1 deletions
+15 -1
View File
@@ -16,6 +16,14 @@ class Mustache_Autoloader
{
private $baseDir;
/**
* An array where the key is the baseDir and the key is an instance of this
* class.
*
* @var array
*/
static private $instances;
/**
* Autoloader constructor.
*
@@ -45,7 +53,13 @@ class Mustache_Autoloader
*/
public static function register($baseDir = null)
{
$loader = new self($baseDir);
$key = $baseDir ? $baseDir : 0;
if (!isset(self::$instances[$key])) {
self::$instances[$key] = new self($baseDir);
}
$loader = self::$instances[$key];
spl_autoload_register(array($loader, 'autoload'));
return $loader;
+17
View File
@@ -33,4 +33,21 @@ class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase
$loader->autoload('\Mustache_Bar');
$this->assertTrue(class_exists('Mustache_Bar'));
}
/**
* Test that the autoloader won't register multiple times.
*
* @return void
*/
public function testRegisterMultiple()
{
$numLoaders = count(spl_autoload_functions());
Mustache_Autoloader::register();
Mustache_Autoloader::register();
$expectedNumLoaders = $numLoaders + 1;
$this->assertCount($expectedNumLoaders, spl_autoload_functions());
}
}