要从controller传递变量到view,需要使用set method。基本的用法是
$this->set('categories',$categories);
更顺手的写法是
$this->set(compact('categories'));
多个变量时可以这样写
$this->set('categories',$categories);
$this->set('category',$category);
也可以这样写
$this->set(array('category','categories'),array($category,$categories));
更顺手的写法是
$this->set(compact('category','categories'));
因为set会检查输入的参数来做不同的应对:
function set($one, $two = null) {
$data = array();
if (is_array($one)) {
if (is_array($two)) {
$data = array_combine($one, $two);
} else {
$data = $one;
}
} else {
$data = array($one => $two);
}
foreach ($data as $name => $value) {
if ($name === 'title') {
$this->pageTitle = $value;
} else {
if ($two === null && is_array($one)) {
$this->viewVars[Inflector::variable($name)] = $value;
} else {
$this->viewVars[$name] = $value;
}
}
}
}
我不用framework时也会在写一个类似的method来实现这种灵活的变量传递。但需要注意的是cakephp中有这个步骤
if ($two === null && is_array($one)) {
$this->viewVars[Inflector::variable($name)] = $value;
}
陷阱就在这里。当我们使用compact来给set传递一个array参数时,将被设置的变量名会被作一些额外的处理。
set(compact(‘category’))是完全没问题的,在view中可以得到$category。但如果set(compact(‘category_id’)),在view中得到的变量叫做$categoryId,而非$category_id。
如果我们要在view中得到的变量名为$category_id,就只能老老实实的写
$this->set('category_id',$category_id);
