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

This commit is contained in:
Jeremy Harris 2011-01-09 18:27:44 -08:00
parent 65d1c0329c
commit 1f1d920ff7
2 changed files with 45 additions and 5 deletions

View file

@ -57,6 +57,16 @@ class ComponentCollection extends ObjectCollection {
* Loads/constructs a component. Will return the instance in the registry if it already exists.
* You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it.
* Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled.
*
* You can alias your component as an existing component by setting the 'alias' key, i.e.,
* {{{
* public $components = array(
* 'AliasedEmail' => array(
* 'alias' => 'Email'
* );
* );
* }}}
* All calls to the `Email` component would use `AliasedEmail` instead.
*
* @param string $component Component name to load
* @param array $settings Settings for the component.
@ -65,8 +75,12 @@ class ComponentCollection extends ObjectCollection {
*/
public function load($component, $settings = array()) {
list($plugin, $name) = pluginSplit($component);
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];
}
$componentClass = $name . 'Component';
if (!class_exists($componentClass)) {
@ -83,12 +97,12 @@ class ComponentCollection extends ObjectCollection {
));
}
}
$this->_loaded[$name] = new $componentClass($this, $settings);
$this->_loaded[$alias] = new $componentClass($this, $settings);
$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,12 @@
App::import('Component', array('Cookie', 'Security'));
App::import('Core', 'ComponentCollection');
/**
* Extended CookieComponent
*/
class CookieAliasComponent extends CookieComponent {
}
class ComponentCollectionTest extends CakeTestCase {
/**
* setup
@ -58,6 +64,26 @@ class ComponentCollectionTest extends CakeTestCase {
$this->assertSame($result, $this->Components->Cookie);
}
/**
* Tests loading as an alias
*
* @return void
*/
function testLoadWithAlias() {
$result = $this->Components->load('CookieAlias', array('alias' => 'Cookie', 'somesetting' => true));
$this->assertInstanceOf('CookieAliasComponent', $result);
$this->assertInstanceOf('CookieAliasComponent', $this->Components->Cookie);
$this->assertTrue($this->Components->Cookie->settings['somesetting']);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
$result = $this->Components->load('Cookie');
$this->assertInstanceOf('CookieAliasComponent', $result);
}
/**
* test load and enable = false
*