baur79
baur79

Reputation: 273

How to add helper or component on-the-fly with the controller action method

i don't want to add it as below cause i needed them only once in certain action method

(so do not useless load the memory)

class UsersController extends AppController {
    var $name = 'Users';
    var $helpers = array('Html', 'Session');
    var $components = array('Session', 'Email');

Upvotes: 3

Views: 4709

Answers (3)

mark
mark

Reputation: 21743

I use a component for adding helpers and components on the fly:

$this->Common->addHelper('Tools.Datetime');
$this->Common->addHelper(array('Text', 'Number', ...));
$this->Common->addComponent('RequestHandler');
$this->Common->addLib(array('MarkupLib'=>array('type'=>'php'), ...));

etc

The complete code to this can be seen in the cakephp enhancement ticket I just opened: http://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/1277

Or with php markup: http://www.dereuromark.de/2010/11/10/loading-classes-on-the-fly/

It also fixes some minor problems with the solution posted by mtnorthrop. Plugins as well as passed options are now possible. Have fun.

Upvotes: 0

Mark Northrop
Mark Northrop

Reputation: 2623

You can load helpers using

$this->helpers[] = 'MyHelper';

as Rob mentioned above, but this won't work for controllers because they have their initialize and startup methods that need to be called in order for them to work.

I've come across a bit of code on the web for loading components inside of a controller action: ComponentLoaderComponent

Yes, it is a component but it isn't very big so it shouldn't be a problem to include it in your controllers.

Either that or you can just study it to see how the component loading works and then write your own controller action to do the same.

Upvotes: 0

Rob Wilkerson
Rob Wilkerson

Reputation: 41236

class UsersController extends AppController {
  public function method_name() {
    $this->helpers[] = 'MyHelper'
  }
}

More on this in the documentation.

Hope that helps.

Upvotes: 7

Related Questions