Allowed helpers to be aliased by setting the 'alias' key

This commit is contained in:
Jeremy Harris 2011-01-09 18:27:53 -08:00
parent 1f1d920ff7
commit 9749dc808d
2 changed files with 47 additions and 6 deletions

View file

@ -41,6 +41,16 @@ class HelperCollection extends ObjectCollection {
* can set `$settings['enabled'] = false` to disable callbacks. This alias is provided so that when
* declaring $helpers arrays you can disable callbacks on helpers.
*
* You can alias your helper as an existing helper by setting the 'alias' key, i.e.,
* {{{
* public $components = array(
* 'AliasedHtml' => array(
* 'alias' => 'Html'
* );
* );
* }}}
* All calls to the `Html` helper would use `AliasedHtml` instead.
*
* @param string $helper Helper name to load
* @param array $settings Settings for the helper.
* @return Helper A helper object, Either the existing loaded helper or a new one.
@ -49,8 +59,13 @@ class HelperCollection extends ObjectCollection {
public function load($helper, $settings = array()) {
list($plugin, $name) = pluginSplit($helper, true);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
$alias = $name;
if (isset($settings['alias'])) {
$alias = $settings['alias'];
}
if (isset($this->_loaded[$alias])) {
return $this->_loaded[$alias];
}
$helperClass = $name . 'Helper';
if (!class_exists($helperClass)) {
@ -67,17 +82,17 @@ class HelperCollection extends ObjectCollection {
));
}
}
$this->_loaded[$name] = new $helperClass($this->_View, $settings);
$this->_loaded[$alias] = new $helperClass($this->_View, $settings);
$vars = array('request', 'theme', 'plugin');
foreach ($vars as $var) {
$this->_loaded[$name]->{$var} = $this->_View->{$var};
$this->_loaded[$alias]->{$var} = $this->_View->{$var};
}
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->_enabled[] = $name;
$this->_enabled[] = $alias;
}
return $this->_loaded[$name];
return $this->_loaded[$alias];
}
}

View file

@ -20,6 +20,13 @@
App::import('Core', 'HelperCollection');
App::import('View', 'View');
/**
* Extended HtmlHelper
*/
App::import('Helper', 'Html');
class HtmlAliasHelper extends HtmlHelper {
}
class HelperCollectionTest extends CakeTestCase {
/**
* setup
@ -56,6 +63,25 @@ class HelperCollectionTest extends CakeTestCase {
$this->assertTrue($this->Helpers->enabled('Html'));
}
/**
* Tests loading as an alias
*
* @return void
*/
function testLoadWithAlias() {
$result = $this->Helpers->load('HtmlAlias', array('alias' => 'Html'));
$this->assertInstanceOf('HtmlAliasHelper', $result);
$this->assertInstanceOf('HtmlAliasHelper', $this->Helpers->Html);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Helpers->enabled('Html'));
$result = $this->Helpers->load('Html');
$this->assertInstanceOf('HtmlAliasHelper', $result);
}
/**
* test that the enabled setting disables the helper.
*