jump to navigation

Calling a helper from a component or controller February 11, 2006

Posted by rossoft in CakePHP.
trackback

Someone asked me in the #cakephp on irc.freenode.net about calling a method of a helper from a component.
I think that this is a bad practice, but sometimes these hacks makes your life easier, and CakePHP wants it so…

I hacked the OutputComponent of rdBloggery (and updated to RC4 components model, making use of the startup method.
Put these code on /app/controllers/components/output.php (the other content not related to the helper-part is omitted…)

class OutputComponent extends Object {
var $view;
var $controller;
function startup(&$controller)
{
$this->controller=& $controller;
$this->view =& new View($controller);
}

function & returnHelper($helper) 
	{ 
		$loaded=array(); 
		$loadedHelpers=& $this->view->_loadHelpers($loaded, array($helper)); 
		$helper=& $loadedHelpers[$helper]; 
        if(isset($helper->helpers) && is_array($helper->helpers)) 
        { 
        	foreach($helper->helpers as $subHelper) 
           	{ 
               	$helper->{$subHelper} =& $loadedHelpers[$subHelper]; 
           	} 
        } 
		return $helper;			 
	}
}

Then, in your controller / component, include the component:

var $components=array('xxx','yyy','output');
Finally, use this in your controller / component:

$helper = $this->output->returnHelper('myhelper');

$helper->myfunc($param);

Advertisements

Comments»

1. peroksid - March 27, 2006

one comment. i use CakePHP – and maybe – it worked earlier – now you must write
$helper = $this->output->returnHelper(’myhelper’);

2. rossoft - March 27, 2006

yes, it’s a typo error

3. oth - May 5, 2006

for typos, you might want to correct them in the post, not everyone reads the comments.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: