Zend_Controllerを使ったWebアプリケーションで、ルーティングを定義してみます。
chkというモジュールを作成した場合、デフォルトでは次のようなURLで、アクセスできます。
http://ドメイン/chk
これを次のようなURLでアクセスできるようにしてみます。
http://ドメイン/testchk
前回のサンプルにchkモジュールとblogモジュールを追加して動作を確認します。
ルーティング
モジュール名とモジュールを配置するディレクトリの対応は次のようにします。
| モジュール名 | モジュール配置ディレクトリ |
|---|---|
| default | BASEDIR/webapp05/modules/default |
| chk | BASEDIR/webapp05/modules/chk |
| blog | BASEDIR/webapp05/modules/blog |
デフォルトのルーティング
デフォルトコントローラ(index)、デフォルトアクション(index)に対応するURLは、次のようになります。
| モジュール名 | URL |
|---|---|
| default |
http://サンプル/ http://サンプル/index http://サンプル/index/index http://サンプル/default/index http://サンプル/defalut/index/index |
| chk |
http://サンプル/chk http://サンプル/chk/index http://サンプル/chk/index/index |
| blog |
http://サンプル/blog http://サンプル/blog/index http://サンプル/blog/index/index |
ルーティングの変更
ディスパッチループに入る前に次のようにルートをルーターに追加します。
-
// $frontは、フロントコントローラオブジェクト
-
-
$router = $front->getRouter();
-
-
// ルートを定義
-
-
$route = new Zend_Controller_Router_Route(
-
':controller/:action/*',
-
'module'=>'default',
-
'controller'=>'index',
-
'action'=>'index',
-
)
-
);
-
$router->addRoute('default', $route);
-
-
$route = new Zend_Controller_Router_Route(
-
'testchk/:controller/:action/*',
-
'module'=>'chk',
-
'controller'=>'index',
-
'action'=>'index',
-
)
-
);
-
$router->addRoute('name_testchk', $route);
-
-
$route = new Zend_Controller_Router_Route(
-
'blog/:controller/:action/*',
-
'module'=>'blog',
-
'controller'=>'index',
-
'action'=>'index',
-
)
-
);
-
$router->addRoute('name_blog', $route);
マニュアル(7.5.3. 基本的な RewriteRouter の操作法)に、次の記述があります。
一番最後にマッチしたルートが適用されるので、 汎用的なルートは最初に定義するようにしましょう。
defaultのルートを最後に追加すると、他のモジュールへルーティングされず、エラーコントローラで処理されることになります。
変更後のルーティング
ルーティングを変更した後は、次のようなURLでモジュールにアクセスできます。
| モジュール名 | URL |
|---|---|
| default | http://サンプル/:controller/:action |
| chk | http://サンプル/testchk/:controller/:action |
| blog | http://サンプル/blog/:controller/:action |
:controllerはコントローラ名、:actionはアクション名です。
:controller名のデフォルトはindex、:actionのデフォルトはindexで、省略可能です。
メモ
今回変更したルートでは、defaultモジュールのルーティングが、デフォルトと違った振る舞いをします。
ルーティングの変更前は、次のURLでルーティング可能です。
http://サンプル/default/:controller/:actoin
ルーティング変更後は、このURLではアクセスできなくなります。
defaultモジュールは、次の形式でのアクセスのみとなります。
http://サンプル/:controller/:actoin
サンプルダウンロード
ダウンロードページにアーカイブしたファイルを置きました。