views:

203

answers:

2

Howdy,

Got question, maybe even problem while creating CakePHP Component. Basically, I need to implement few quesries that can be accesses everywhere in my layout (sidebar statistics and so).

When I try to query in Component, I got error about calling function on a non-object.

Damn, can anybody explain me this one?

Cheers!

+1  A: 

Are you doing something like this?

class MyComponent extends object {
  function startup(&$controller) {
    $this->controller = $controller; // Stores reference Controller in the component
  }
  function common() {
    $data = ClassRegistry::init('MyModel')->myQuery(); // Call the query on the model
    $this->controller->set(compact('data')); // Sets data from myQuery in view
  }
}
neilcrookes
+1 This solution is better than mine because it not only loads the model, but instantiates it. I forgot about that when I provided my own answer.
Rob Wilkerson
Holy Mother! This is what I want! Thanks a lot!
Johannes
A: 

At the risk of sounding pedantic, you'd be violating MVC pretty egregiously by doing this. If you're okay with that, you can use App::import() to load any model from anywhere in your app (http://book.cakephp.org/view/531/Importing-Controllers-Models-Components-Behaviors-).

If you're interested in attempting to retain the MVC structure, we may be able to help with some more information about the queries you need to run in that generic manner.

Rob Wilkerson
Rob, I tried this but I needed to screw somethings up. Every hour I learn something new about CakePHP :)
Johannes