CakePHP: Can you query a database from a helper class?

Hi, you just need to know if you can query the database from inside the helper class, if you should and how you do it.

thanks

+4
source share
2 answers

You could by passing the model reference to the view as a variable via $ this-> set (), and then requesting it ... but you shouldn't. It is dirty; -)

CakePHP uses the MVC model, and helpers are part of View (V of MVC) - their task is to display the (already available) information passed to it from the controller.

If your view needs more information, your controller should already have requested Models to receive it.

I would advise you to familiarize yourself with the MVC model, if you are not familiar with it, then some refactoring may be in order!

+3
source

Yes. You can query the database from your auxiliary file. Check this: -

class YourHelperNameHelper extends AppHelper { function queryDbFromHelper() { // Load your model here App::import('Model','ModelName'); $this->ModelName = new ModelName(); //now you can use find method or another method to query DB. return $this->ModelName->find('all'); } } // Include this helper in controller var $helpers = array('YourHelperName'); // call this function in helper file. $this->YourHelperName->queryDbFromHelper(); 
+1
source

All Articles