第3章
第3章 · 初心者向け

Controllerの基本

Controllerは「受付」。受け取って、処理して、画面へ渡す係です。

1. Controllerの作り方・読み方

名前は 〇〇Controller。ファイル名も同じ
namespace App\Controller;

class TodosController extends AppController
{
    public function index()
    {
    }
}
  • extends AppController共通の土台を引き継ぐ(第1章の継承)
  • index()一覧用の窓口(Action)

2. Actionとは

Action=1リクエストの入り口になる public メソッド

よく使う名前(覚えると楽):

  • index … 一覧
  • view … 詳細
  • add … 新規
  • edit … 編集
  • delete … 削除

3. $this が何を指しているか

Controllerの中の $this=今動いている受付係そのもの
$this->getRequest();  // お客さんの注文内容
$this->set(...);      // 厨房から来た料理をトレーに載せる
$this->redirect(...); // 別の窓口へ案内する

第1章の $this と同じ考え方です。

4. Requestとは

Request=ブラウザから届いた荷物(URL・入力・ボタンなど)
$request = $this->getRequest();

5. GETパラメータの取得

URLの ? 以降です。例: /todos?status=done

$status = $this->request->getQuery('status');
// $status は 'done'
覚え方

GET=見える荷物(URLに出る)。検索やページ番号によく使います。

6. POSTデータの取得

フォーム送信など、URLに出さない荷物です。

if ($this->request->is('post')) {
    $title = $this->request->getData('title');
    $data = $this->request->getData(); // 全部
}
大事

「POSTで来たときだけ保存する」と is('post') で確認するのが基本です。

7. URLパラメータの取得

/todos/view/55 は、メソッドの引数で受け取ることが多い
public function view($id = null)
{
    // /todos/view/5 なら $id は 5
}

8. $this->set() でViewへデータを渡す

set=画面側で使える変数を渡す
$this->set('title', '買い物');
// View で $title が使えるようになる
たとえ

受付がトレーにメモを載せて、盛り付け係(View)に渡すイメージです。

9. Redirect

保存などのあと、「別のURLへ移動させる」
return $this->redirect(['action' => 'index']);
// 一覧へ戻す、が定番

10. エラー処理の基本

「無いのに詳細を見ようとした」などは、例外で止めます。

use Cake\Http\Exception\NotFoundException;

public function view($id = null)
{
    if (!$id) {
        throw new NotFoundException('見つかりません');
    }
}
今はこれだけでOK

ユーザー向けメッセージは Flash、詳しい記録はログ(後の章)。まずは「止める方法がある」と知れば十分です。

第3章 やってみよう

EXERCISE
  1. GETで名前を受け取る Action を想像して書く
  2. set で View に渡す1行を書く
  3. 保存後に一覧へ redirect する1行を書く