views:

47

answers:

4

Hi, Iv got a method in a model that I want to be executed everytime a page is requested so I think I need to call it from the app_controller but can't seem to get it to work. The model i want to use is called Blacklist and it has a method in it called check_blacklist() which is what I want to run every time a page is requested. Does anyone know how I should do it?

Thanks

+6  A: 

Well, one way to do that would be adding:

var $uses = array('Blacklist');

In your AppController class.

Perhaps a better solution is using a CakePHP built-in method called: loadModel, like this:

$this->loadModel('Blacklist');

If you add Blacklist in the $uses array in your AppController, it will be available in all of your controllers, loadModel just loads the Model for a specific task.

PawelMysior
+1  A: 

Try to avoid using the $uses array as it adds some overhead to all actions, whether or not the model is used in that action.

As Pawel says, you can use $this->loadModel('Blacklist'); It should be located in the action, say view, just before $this->Blacklist->check_blacklist()

e.g.

function view($id)
{
    if($id)
    {
        $this->loadModel('Blacklist');
        $this->Blacklist->check_blacklist();
        ...
    }
}

If this is very widely used, I'd probably write the function on app_model.


Edit:

Use of loadModel is covered here: http://book.cakephp.org/view/845/loadModel

Leo
A: 

$ModelName = ClassRegistry::init('ModelName');

$ModelName->find();

mark
A: 

Unfortunately, due to bug #858, your best bet is to avoid using loadModel() in AppController for now, unless you aren't using any plugins (quite possible). The solution I used to replace $uses was along the lines of:

$this->Blacklist = ClassRegistry::init('Blacklist');
$this->Blacklist->check_blacklist();

Note that you should put this in your beforeFilter() or beforeRender() (see the cookbook) - depending on when you want it executed...

If you'd like to use that same code in other sites, or have it fire earlier in the loading chain, you might consider a Component - putting the same code in your Component initialize() function, or startup() function if the point in the load chain is less critical.

michaelc
That's a bit of a heavy handed statement - not far off saying 'because there are bugs it would be best to avoid using CakePHP for a while'. I haven't ever needed to use plugins in a CakePHP application, and I've built a few. My reading of #858 is that it would be inadvisable to use loadModel in the plugin itself.
Leo
If you're going to do this in the beforeFilter, you may as well use $uses.
Leo

related questions