Merge pull request #305 from hcpss-banderson/feature/avoid-multuple-autoloaders
Prevent redundant autoloader registerations. Fixes #304
This commit is contained in:
@@ -16,6 +16,14 @@ class Mustache_Autoloader
|
|||||||
{
|
{
|
||||||
private $baseDir;
|
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.
|
* Autoloader constructor.
|
||||||
*
|
*
|
||||||
@@ -45,7 +53,13 @@ class Mustache_Autoloader
|
|||||||
*/
|
*/
|
||||||
public static function register($baseDir = null)
|
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'));
|
spl_autoload_register(array($loader, 'autoload'));
|
||||||
|
|
||||||
return $loader;
|
return $loader;
|
||||||
|
|||||||
@@ -33,4 +33,21 @@ class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase
|
|||||||
$loader->autoload('\Mustache_Bar');
|
$loader->autoload('\Mustache_Bar');
|
||||||
$this->assertTrue(class_exists('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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user