diff --git a/lib/Cake/Cache/Cache.php b/lib/Cake/Cache/Cache.php index 938df43189e..c6f54759c7b 100644 --- a/lib/Cake/Cache/Cache.php +++ b/lib/Cake/Cache/Cache.php @@ -156,11 +156,12 @@ protected static function _buildEngine($name) { if (!is_subclass_of($cacheClass, 'Cake\Cache\CacheEngine')) { throw new Error\CacheException(__d('cake_dev', 'Cache engines must use Cake\Cache\CacheEngine as a base class.')); } - static::$_engines[$name] = new $cacheClass(); - if (static::$_engines[$name]->init($config)) { - if (static::$_engines[$name]->settings['probability'] && time() % static::$_engines[$name]->settings['probability'] === 0) { - static::$_engines[$name]->gc(); + $engine = new $cacheClass(); + if ($engine->init($config)) { + if ($engine->settings['probability'] && time() % $engine->settings['probability'] === 0) { + $engine->gc(); } + static::$_engines[$name] = $engine; return true; } return false; @@ -204,16 +205,18 @@ public static function drop($config) { * triggered. * * @param string $config The configuration name you want an engine. + * @param Cake\Cache\CacheEngine $engine An engine instance if you are manually + * injecting a cache engine. * @return Cake\Cache\Engine */ - public static function engine($config) { + public static function engine($config, CacheEngine $engine = null) { if (Configure::read('Cache.disable')) { return false; } if (isset(static::$_engines[$config])) { return static::$_engines[$config]; } - if (!static::_buildEngine($config)) { + if (!$engine && !static::_buildEngine($config, $engine)) { $message = __d( 'cake_dev', 'The "%s" cache configuration does not exist, nor could configuration be found at "Cache.%s".', @@ -222,6 +225,9 @@ public static function engine($config) { ); trigger_error($message, E_USER_WARNING); } + if ($engine) { + static::$_engines[$config] = $engine; + } return static::$_engines[$config]; } diff --git a/lib/Cake/Test/TestCase/Cache/CacheTest.php b/lib/Cake/Test/TestCase/Cache/CacheTest.php index e979fb255d8..43ae9da8990 100644 --- a/lib/Cake/Test/TestCase/Cache/CacheTest.php +++ b/lib/Cake/Test/TestCase/Cache/CacheTest.php @@ -154,11 +154,22 @@ public function testDecrementNonExistingConfig() { public function testAttemptingToConfigureANonCacheEngineClass() { $this->getMock('\StdClass', array(), array(), 'RubbishEngine'); Configure::write('Cache.wrong', array( - 'engine' => __NAMESPACE__ . '\Rubbish' + 'engine' => '\RubbishEngine' )); Cache::engine('wrong'); } +/** + * Test that engine() can be used to inject instances. + * + * @return void + */ + public function testSetEngineValid() { + $engine = $this->getMockForAbstractClass('\Cake\Cache\CacheEngine'); + Cache::engine('test', $engine); + $this->assertSame($engine, Cache::engine('test')); + } + /** * test that calling config() sets the 'default' configuration up. *