22

How do I use a model in a component in CakePHP?

In a controller you can use

public $uses = array(...);

but that doesn't work in a Component.

What does?

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
AgeDeO
  • 3,137
  • 2
  • 25
  • 57

3 Answers3

35

Try this code:

$model = ClassRegistry::init('Yourmodel');

Simple query with your model into your component

$result= $model->find('all');
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
14

You could do it this way:

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

But it is suppose you don't use Models inside components.

Alvaro
  • 40,778
  • 30
  • 164
  • 336
3

If you need the current Model you can use the initialize() or startup() callback of the Component.

public function initialize(Controller $controller) {
    $this->Controller = $controller;
    $this->Model = $this->Controller->{$this->Controller->modelClass};
    $this->modelAlias = $this->Model->alias;
    parent::initialize($controller);
}

Now you can access the model everywhere in your component.

public function countAllItems() {
    return $this->Model->find('count');
}
Mathieu
  • 46
  • 4