【问题标题】:cakephp session writing in appcontroller在 appcontroller 中编写 cakephp 会话
【发布时间】:2014-09-10 19:36:03
【问题描述】:

我有一个要在所有页面上运行的访问者日志记录脚本
所以我把它保存在 appController 的 beforeFilter 方法中,如下所示

public function beforeFilter() { 
    //log visitors starts here
    if( $this->Session->check('visited') == true )
    {
        //logging code
    }
    else
    {
        $this->Session->write('visited') = true;  //this line gives error
    }
    //log visitors ends here
}

我收到以下错误

 Fatal error: Class declarations may not be nested in D:\wamp\www\myproject\lib\Cake\Error\ExceptionRenderer.php on line 54

通过注释如下所示的会话编写行,页面运行时不会出现 ant 错误

$this->Session->write('visited') = true;    

我也将此代码更改为 afterFilter 和 beforeRender 方法,但仍然错误

【问题讨论】:

    标签: php session cakephp


    【解决方案1】:

    您可以改用 CakeSession:

    public function beforeFilter() { 
        if( CakeSession::check('visited') ){
            //logging code
        } else {
            CakeSession::write('visited', true);
        }
    }
    

    来源:https://book.cakephp.org/2.0/en/development/sessions.html

    【讨论】:

      【解决方案2】:

      根据文档:http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::write

      public function beforeFilter() { 
          //log visitors starts here
          if( $this->Session->check('visited') ) // No need to check == true
          {
              //logging code
          }
          else
          {
              $this->Session->write('visited', true);  //Second param to set the value
          }
          //log visitors ends here
      }
      

      【讨论】:

      • 此已删除错误但未设置会话,并且每次刷新时它都会执行 IF 部分而不是页面引用的其他部分。
      • 如果它执行if语句,则意味着你的会话已经包含一个名为'visited'的变量,如果变量存在,check将返回true,如果你想测试'的值已访问',使用:$this->Session->check('visited') && $this->Session->read('visited') == true
      猜你喜欢
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2015-04-02
      • 2011-05-14
      • 2011-05-13
      相关资源
      最近更新 更多