【问题标题】:cakephp3 read session in componentcakephp3 在组件中读取会话
【发布时间】:2015-06-15 07:12:08
【问题描述】:

我有一个为 cakephp3 开发的插件,我想在我的组件内部读取存储在会话中的值。

在 cakephp 2 中我使用过:

$userId = CakeSession::read('Auth.User.id');

但如果我将它用于 cakephp 3,则返回此错误:

Error: Call to undefined method UserPermissions\Controller\Component\UserPermissionsComponent::_hasSession() 
File /Users/info/Sites/cakephp3/vendor/cakephp/cakephp/src/Network/Session.php 
Line: 382

在我正在使用的组件中包含会话:

use Cake\Network\Session;

如何在会话中读取值? 谢谢

【问题讨论】:

  • 您始终可以使用$this->controller->request->session() 拉取它,但您需要先设置$this->controller。这样你就不需要使用use Cake\Network\Session.. 我做过类似的事情,所以你可以在这里查看github.com/akkaweb/AKKA-CakePHP-Facebook-Plugin/blob/master/src/…
  • 我将剖析代码并将其作为评论放在下面.. 2 分钟

标签: php session cakephp cakephp-3.0


【解决方案1】:

我会在您的 initialize() 方法中实现这一点:

use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;

class YourComponent extends Component{

    public $controller = null;
    public $session = null;

    public function initialize(array $config)
    {
        parent::initialize($config);
        // ....

        /**
         * Get current controller
        */
        $this->controller = $this->_registry->getController();

        $this->session = $this->controller->request->session();

        // You can then use $this->session in any other methods        
        // If debug = true else use print_r() to test
        debug($this->session->read('Auth.User.id')); 
    }        
}

【讨论】:

  • 我不确定这种方式的会话是否正常工作,例如如果我添加这个:$this->session->setFlash($message);返回错误:调用未定义的方法 Cake\Network\Session::setFlash()
  • SessionComponent::setFlash() 已弃用。您应该改用 Flash。 book.cakephp.org/3.0/en/appendices/3-0-migration-guide.html ...我在我的插件中使用它就好了。我没有尝试设置任何消息,但我认为您只需要阅读它即可。您可以随时使用write 写入会话
  • 使用 Flash 我再次遇到同样的错误:致命错误:调用未定义的方法 Cake\Network\Session::Flash()
  • 我不是故意让您那样使用它...您必须将 Flash 组件添加到您的组件中才能这样工作...如果您想要做的只是设置消息。我真的以为你的问题是关于阅读 Session.... book.cakephp.org/3.0/en/controllers/components/flash.html
  • public $components = ['Flash'];
猜你喜欢
  • 2018-02-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2012-01-11
  • 2013-08-03
  • 2018-12-08
  • 2015-04-28
相关资源
最近更新 更多