[CakePHP] GETでパラメタ・コントローラ名・アクション名を取得

CakePHP2でURLからコントローラー名・アクション名・パラメタなどを取得する方法です。コントローラ名・アクション名・パラメタの取得は、CakePHPでウェブを構築する上で最も利用頻度の多い作業の一つではないでしょうか。Ver1.3とは取得方法が変わっているので注意が必要です。
Contents
バージョンによる違い(GET取得)
Ver1.3から取得方法が変わりましたので、以下の表に違いをまとめておきます。
Ver1.3 | Ver2.x |
---|---|
$this->data | $this->request->data |
$this->params['url']['url'] | $this->request->url |
$this->params['contoller'] | $this->request->controller |
$this->params['action'] | $this->request->action |
$this->params['named'] | $this->request->named |
$this->params['pass'] | $this->request->pass |
Ver2.xからは$this>request>取得内容の形式に統一されたので、覚えやすいですね。
利用方法
というURLの各種データを取得してみます。
「http://www.example.com/posts/index/7/?page=2&sort=asc」
CakePHP方式のURLでは「?id=7」という形だけではなく、「/7/」という表記ができるようになっています。この「/7/」を取得するのは「$this->request->pass」になっています。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php pr($this->request->url); // 表示データ:posts/index/7 pr($this->request->controller); // 表示データ:posts pr($this->request->action); // 表示データ:index pr($this->request->pass); // 表示データ:Array([0]=>7) ?> |
通常のパラメタの部分(?page=2&sort=asc)は以下のように取得します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php pr($this->request->query); Array ( [url] => indexs/index/7/ [page] => 2 [sort] => asc ) //変数に代入する $page=$this->request->query['page']; $sort=$this->request->query['sort']; ?> |
関連記事
- [CakePHP] 別のコントローラにあるアクションを利用する方法
- [Laravel] Getの値をコントローラーで取得する方法
- [CakePHP] トップページ(ホームページ)を設定する方法
- [CakePHP] Not Found The requested URL 〜was not found on this server. エラー対処方法
- [CakePHP] 独自のSQL文を利用する方法