LoginSignup
3
1

More than 1 year has passed since last update.

CakePHP4のコンポーネントからコントローラーとリクエストを利用するメモ

Last updated at Posted at 2021-07-06

CakePHP4でコンポーネントからコントローラーとリクエストを呼び出せなくて、悩んだのでメモ

結論

以下のように書く。

class SampleComponent extends Component {

  private $controller;
  private $request;

  public function beforeFilter()
  {
      $this->controller = $this->getController();
      $this->request = $this->controller->getRequest();
  }
}

ちなみに以下は、ダメだった

class SampleComponent extends Component {

  private $controller;
  private $request;

  public function beforeFilter()
  {
      $this->controller = $this->getController();
      // Controllerクラスの$requestプロパティはproctedなので、アクセスできない
      $this->request = $this->controller->request;
  }
}

補足

公式ドキュメントには書いてなかったので、ちょっと苦労した、、

CakePHP4ので入っているRequestHandlerComponentのソースコードを読んだらわかった。ソースコードをちゃんと読むのは大切ですね。

参考

3
1
2

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
3
1