7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【CakePHP3.6 以降】コンポーネントでセッションを利用する方法

Last updated at Posted at 2019-02-22

コンポーネントでセッションを利用する方法を検索して、
いろんな記事を参考に試してみたが、どれも上手くいかなかった。。。

辛抱強く調べてみるとバージョン3.6以降ではセッションオブジェクトの呼び出し方法が変わっていることが、上手くいかない原因のようでした。(レシピブックにもちゃんと書かれていました。。。詳しくはこちら
3.6以降でコンポーネントでセッションを利用する方法を紹介させていただきます。
##CakePHP3.6以降

SampleComponent.php
namespace App\Controller\Component;

use Cake\Controller\Component;

/**
 * Common component
 */
class SampleComponent extends Component
{
  protected $_defaultConfig = [];

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

    $this->controller = $this->_registry->getController();

    $this->session = $this->controller->getRequest()->getSession();
  }

    public function testWrite()
    {
        $this->session->write('test', 'test');
    }
 
    public function testRead()
    {
        $this->session->read('test');
    }
}

ご参考になれば幸いです!

7
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?