Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@tsukahara-akito

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

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

辛抱強く調べてみるとバージョン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');
    }
}

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

6
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
6
Help us understand the problem. What is going on with this article?