关于cakePHP中Set()组件的一个问题

关于cakePHP中Set()组件的一个问题,cakephp,cakephp-1.2,Cakephp,Cakephp 1.2,我正在使用cakePHP 1.26。 在控制器中,我得到一个函数: function testing(){ $userinfo=$this->Test->findAllByuser_id(); $this->set('userinfo',$userinfo); } 我发现包含一些数组数据的变量“userinfo”只能在testing.ctp中访问。 为了使其他.ctp文件可以访问变量“userinfo”,我使用了以下帮助程序: $this->Session->w

我正在使用cakePHP 1.26。
在控制器中,我得到一个函数:

function testing(){
$userinfo=$this->Test->findAllByuser_id();
$this->set('userinfo',$userinfo);
}
我发现包含一些数组数据的变量“userinfo”只能在testing.ctp中访问。
为了使其他.ctp文件可以访问变量“userinfo”,我使用了以下帮助程序:

 $this->Session->write('userinfo', $userinfo);     
但是,我不知道为什么Set()函数定义的变量不能被其他.ctp文件访问,但是会话可以访问。
使用其他方法而不是使用会话是否有做同样事情的最佳方法?

请告知。

一般来说,控制器的每个方法仅与其视图通信(即
ctp
文件,位于根据控制器名称命名并根据方法名称命名的文件夹中)。如果此控制器名为
Tests
,则其
testing()
方法中的变量
set()
将仅对标识为
views/Tests/testing.ctp
ctp
文件可用

要使该信息在其他地方可用,您必须将其持久化(就像在会话中所做的那样),或者通过“外部”方法(如
requestAction()
)执行控制器


作为起点,只需了解控制器的给定方法直接与一个且仅与一个视图对齐(同样,存在过度简化的风险)。

您还可以将函数封装在模型中

在用户模型中

function getUserinfo($id)
{
    return $this->findByUser_id($id);
}
/*in another controller*/
function someAction($uid)
{
    $this->User = ClassRegistry::init("User"); // or you can use `$uses = array('User');`
    $this->set("userinfo",$this->User->getUserInfo($uid));
}
然后通过初始化用户模型在其他控制器中调用它

function getUserinfo($id)
{
    return $this->findByUser_id($id);
}
/*in another controller*/
function someAction($uid)
{
    $this->User = ClassRegistry::init("User"); // or you can use `$uses = array('User');`
    $this->set("userinfo",$this->User->getUserInfo($uid));
}