Question

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

Thanks

Was it helpful?

Solution

You could, by passing a reference to the Model into the View as a variable via $this->set() and then querying it...but you shouldn't. It's messy ;-)

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

If your view needs extra information , then your controller should have already queried the Models to get it.

I'd suggest you read up on the MVC model if you're not familiar with it, then some refactoring might be in order!

OTHER TIPS

Yes. You can query the database from your helper file. Please 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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top