Search code examples
model-view-controllercachingcakephphelpercontrollers

Is There A Downside To Calling Models From Helpers In CakePHP?


A bit of context: I need to cache the homepage of my CakePHP site - apart from one small part, which displays events local to the user based on their IP address.

You can obviously use the <cake:nocache> tag to dictate a part of the page that shouldn't be cached; but you can't surround a controller-set variable with these tags to make it dynamic. Once a page is cached, that's it for the controller action, as far as I know.

What you can usefully surround with the nocache tags are elements and helpers. As such, I've created an element inside these tags, which calls a helper function to access the model and get the appropriate data. To get at the model from the helper I'm using:

$this->Modelname =& ClassRegistry::init("Modelname");

This seems to me, however, to be a kind of iffy way of doing things, both in terms of CakePHP and general MVC principles. So my question is, is this an appropriate way of getting what I want to do done, or should it ring warning bells? Is there a much better way of achieving my objectives that I'm just missing here?


Solution

  • Other than breaking all the carefully-laid principles of MVC?

    In addition to putting this item into an element, why not fetch it with a trivial bit of ajax?

    1. Put the call in its own controller action, such that the destination URL -> /controller/action (quite convenient!)
    2. Pass the IP back to that action for use in the find call
    3. Set the ajax update callback to target within the element with the results of the call accordingly

    No need to muck around calling Models directly from Views, and no need to bog things down with requestAction. :)

    HTH