いろいろ備忘録

雑記です。

CakePHP3のリバースルーティングとは

New router goodies » Debuggable - Node.js Consulting によると、

 

そもそもリンクの書き方は、文字列での指定と、連想配列での指定の2つがある。

①文字列の場合
$html->link('My post title', '/posts/view/5'
);

連想配列の場合
$html->link('My post title', array(
'controller' => 'posts',
'action' => 'view',
5 ));

後者の場合はリバースルーティングが有効になる。

すぐに localhost/posts/view/5 へのリンクを生成せず、routes.php内のRouter::connect()から、controllerとactionが同じものを探し、存在する場合はそのconnect()の第一引数に書き換える。

つまり、②が設定されていて
Router::connect('/hot_posts/*', array('controller' => 'posts', 'action' => 'view')); のように
コントローラとアクションが同じ配列を持つルートが有る場合は、
localhost/posts/view/5 ではなく、localhost/hot_posts/5に書き換える。

もう一つ例を挙げると、

テンプレート(.ctp)にこう書かれていて
$html->link('Top', array(
'controller' => 'Articles',
'action' => 'index' ));
routes.phpにこのように書かれているときは
$routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);

Topをクリックすると localhost/articles/indexではなく、localhost/にアクセスする。