3

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');

baur79
  • 273
  • 5
  • 18

3 Answers3

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

More on this in the documentation.

Hope that helps.

Rob Wilkerson
  • 40,476
  • 42
  • 137
  • 192
0

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.

Mark Northrop
  • 2,613
  • 1
  • 20
  • 21
0

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.

mark
  • 21,691
  • 3
  • 49
  • 71
  • the only other part that is missing: function initialize($Controller = null) { $this->Controller = $Controller; } – mark Nov 09 '10 at 22:33
  • hope the update helps - just opened a ticket for supporting this enhancement – mark Nov 10 '10 at 15:26
  • This doesn't work for the Auth component. The Auth component makes use of the Session and RequestHandler components but when you import and initialize it like that, those two are missing. I had to add them to the Auth component manually. – aiham May 27 '11 at 06:09