Use a model in a component

前端 未结 3 1227
我在风中等你
我在风中等你 2021-02-07 02:07

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

3条回答
  •  孤独总比滥情好
    2021-02-07 02:59

    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');
    }
    

提交回复
热议问题