サイトアイコン マーカーネット株式会社

CakePHPのルーティング例

CakePHPのルーティング例

Webサイトではアドレスの構造は重要です。
CakePHPのルーティングの例について紹介します。

1. Router::connect(‘/index/’, array(‘controller’ => ‘test’, ‘action’ => ‘index’));
「http://xxxxxxxxxxxxx/index/」で、
testコントローラのindex()が呼ばれます
class TestController extends AppController {
function index() {
}
}

2. Router::connect(‘/index2/’, array(‘controller’ => ‘test’, ‘action’ => ‘index2’, 1));
「http://xxxxxxxxxxxxx/index2/」で、
testコントローラのindex2()が呼ばれ、引数に「1」が渡ります。
class TestController extends AppController {
function index2($arg) {
debug($arg); // (int) 1と表示されます
}
}
3. Router::connect(‘/index3/’, array(‘controller’ => ‘test’, ‘action’ => ‘index3’, array(“category” => “テスト”)));
「http://xxxxxxxxxxxxx/index3/」で、
testコントローラのindex3()が呼ばれ、引数に配列「array(“category” => “テスト”)」が渡ります。
class TestController extends AppController {
function index3($args) {
debug($args); // array(‘category’ => ‘テスト’)と表示されます
}
}

4. Router::connect(‘/index4/’, array(‘controller’ => ‘test’, ‘action’ => “index4”, “category” => “テスト2”));
「http://xxxxxxxxxxxxx/index4/」で、
testコントローラのindex4()が呼ばれ、$this->paramsに「array(“category” => “テスト2”)」が設定されます。
class TestController extends AppController {
function index4() {
debug ($this->params[“category”]); // ‘テスト2’と表示されます。
}
}

5. Router::connect(‘/index5/’, array(‘controller’ => ‘test’, ‘action’ => ‘index5’, “prefix” => “admin”));
「http://xxxxxxxxxxxxx/index5/」で、
testコントローラのadmin_index5()が呼ばれます
class TestController extends AppController {
function admin_index5() {
}
}

6. Router::connect(‘/index6/*’, array(‘controller’ => ‘test’, ‘action’ => “index6”));
「http://xxxxxxxxxxxxx/index6/テスト/テスト2/テスト3」で、
testコントローラのindex6()が呼ばれ、「テスト」が$arg1, 「テスト2」が$arg2, 「テスト3」が$arg3に設定されます
class TestController extends AppController {
function index6($arg1, $arg2, $arg3) {
debug ($arg1); // ‘テスト’と表示されます
debug ($arg2); // ‘テスト2’と表示されます
debug ($arg3); // ‘テスト3’と表示されます
}
}

モバイルバージョンを終了