LoginSignup
30
27

More than 5 years have passed since last update.

CakePHP(2.x) のindexアクションのルーティングとパラメータ受け取り

Last updated at Posted at 2014-08-19

デフォルトの動作を見てみる

例としてドメインをhttp://cakephp.devとします。

http://cakephp.dev/hoges/index/1 へのアクセス

デフォルトでは、hogesコントローラーのindexアクションが実行されます。

パラメータの受け取り方

末尾のパラメータ1は、下記のように受け取ることが出来ます。

HogesController.php
// http://cakephp.dev/hoges/index/1 へアクセス
public function index($id) {
    if($id && is_numeric($id)) {
        echo "パラメータ $id を受け取りました";    // 「パラメータ 1 を受け取りました」が出力される
    }
}

http://cakephp.dev/hoges/1 へのアクセス

”index”を省略しただけですが、デフォルトでは末尾の”1”がアクションとして解釈されてしまい、エラーになってしまいます。

Missing Method in HogesController
Error: The action 1 is not defined in controller HogesController

indexアクションのルーティングをしよう

/app/Config/routes.phpにルーティング設定を記述してやると、
indexを省略した際もindexメソッドが実行できるようになります。

routes.php の編集

routes.php
Router::connect("/:controller/:id",
    array("action" => "index", "method" => "GET"),
    array("id"=>"[0-9]+")
);

パラメータを”id”と名付け、正規表現で数字のみの制約をかけています。
これで、http://cakephp.dev/hoges/1 へのアクセスでも、indexアクションにルーティングされるようになりました。

パラメータの受け取り方

$this->request->params['パラメータ名']での受け取りになります。

HogesController.php
// http://cakephp.dev/hoges/1 へアクセス
public function index() {
    if ($this->request->params['id']) {
        $id = $this->request->params['id'];
        echo "パラメータ $id を受け取りました";    // 「パラメータ 1 を受け取りました」が出力される
    }
}

パラメータの受け取り方が二通り…?

無事にindex省略時のルーティングができるようになりました。
ただし、このままでは同じindexアクションに、パラメータの受け取り方が二通りあることになってしまいます。

面倒なので、ルーティングをもう一つ記述します。

routes.php
Router::connect("/:controller/index/:id",
    array("action" => "index", "method" => "GET"),
    array("id"=>"[0-9]+")
);

index付きのURLでアクセスした際も、パラメータを $this->request->params['id'] にセットしてやります。

これでhttp://cakephp.dev/hoges/index/1 でも、http://cakephp.dev/hoges/1 でも、
同じ $this->request->params['id'] にてパラメータを受け取れるようになりました。

ちなみに…

条件に一致しない際は(この例ではid≠数字)、変更前と同じようにメソッド呼び出しになります。

http://cakephp.dev/hoges/fuga へのアクセス

Missing Method in HogesController
Error: The action fuga is not defined in controller HogesController

30
27
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
30
27