LoginSignup
5
2

More than 5 years have passed since last update.

CakePHP2.x で Call to a member function body() on a non-object エラーが出たときの対応

Last updated at Posted at 2018-07-05

いきなり解決策

CakePHP2.x系では、Controller のインスタンス生成時に、 CakeRequest() オブジェクトと CakeResponse() オブジェクトが必要。その設定がされてない場合にこのエラーが出ます。なので、指定すればOK。

// before
new Controller();
// after
new Controller(
    new CakeRequest(),
    new CakeResponse()
);

背景

僕の場合は、とある事情により、Shellで、Controller->render()を実行する必要が出て、その際にこのエラーに遭遇したため、上記対応で解決しました。

コアのソースを見たところ、エラー箇所は以下

// lib/Cake/Controller/Controller.php
 934     public function render($view = null, $layout = null) {
// 省略
 959             }
 960         }
 961
 962         $this->autoRender = false;
 963         $this->response->body($this->View->render($view, $layout)); // ここでエラー
 964         return $this->response;
 965     }

ここで、そもそも、$this->response が空であることがわかったので、コンストラクタを確認

// lib/Cake/Controller/Controller.php
 319     public function __construct($request = null, $response = null) {
// 省略
 340         if ($response instanceof CakeResponse) {
 341             $this->response = $response; // ここでセット
 342         }

なるほど、CakeResponse オブジェクトをセットする必要があると分る。
という流れで調査しました。

おそらく、CakePHP1系では、Controller にこういう引数は無いので、1->2の切り替えをするときに遭遇しそうな不具合(ニッチ)ですが、参考になれば幸いです。

5
2
0

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
5
2