class Cat extend AppModel{
public static function getCat($medium=NULL){
$allcat = $this->Cat->find('all', array('contain' =>false,
'conditions' => array('Cat.c_medium' => $medium),
'order' => array('Cat.c_name' => 'asc')));
return $allcat;
}
}
我想从默认方式访问这个方法。ctp像Cat::getCat('eng');
但是这行不通,请帮帮我。
错误:- Fatal error: Class 'Cat' not found in C:xampphtdocsappViewLayoutsdefault.ctp on line 100
你需要App::uses()你想在你的文件中使用的类。对于视图,通常最好在最顶部的控制器中执行此操作:
<?php
App::uses('Cat', 'Model');
现在可以在所有控制器动作及其视图中访问Cat模型-特别是通过静态访问(对于非静态访问ClassRegistry::init()通常负责包含本身)。
但是你在这里滥用了静态方法。您应该只对非查询方法静态地访问模型。
这里的方法一开始就不应该是静态的。使用控制器调用此方法并将结果向下传递给视图。
你的代码中有一些错误;
-
class Cat extend AppModel
应该是class Cat extendS AppModel
(而不是扩展中额外的's') 在静态方法中使用 - 你在
Cat
模型内部使用$this->Cat->find(...)
,它应该简单地是$this->find(...)
$this
是不可能的。静态方法没有类的"实例"可以引用,因此$this
将产生错误通常,你不会在视图或布局中访问模型。模型在控制器中使用,结果通过提供'viewVars'传递给视图;
//控制器
class MyController extends AppController {
// Specify the Models you want to use
public $uses = array('Cat');
public function my_action()
{
$this->set('my_view_var_name', $this->Cat->getCat('eng'));
}
}
//视图(app/view/My/my_action.ctp):
debug($my_view_var_name);
通过ClassRegistry :: init ()
如果你想要,可以在任何地方获得一个模型的实例,也可以在View/Layout;
ClassRegistry::init('ModelName');
//app内部/View/Layout/default.ctp
$cats = ClassRegistry::init('Cat')->getCat('eng');
debug($cats);
我正在使用这个代码-
试试这个
<?php
$cats = ClassRegistry::init('Cat')->getCat('eng');
pr($cats);
?>