【问题标题】:A question about the Set() component in cakePHP关于 cakePHP 中的 Set() 组件的一个问题
【发布时间】:2010-07-21 16:06:01
【问题描述】:

我正在使用 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 文件访问,但 Session 可以。
有没有最好的方法通过使用其他方法而不是使用 Session 来做同样的事情?
请指教。

【问题讨论】:

    标签: cakephp cakephp-1.2


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      也可以将函数封装在模型中。

      在用户模型中

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

      【讨论】:

        猜你喜欢
        • 2014-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多