第 17 页 共 112 页
控制器是
CController
或者其子类的实例. 用户请求应用时,创建控制器。控制器执行请求 action,action 通常引
入必要的模型并提供恰当的视图。最简单的
action
仅仅是一个控制器类方法,此方法的名字以
action
开始。
控制器有默认的 action。用户请求不能指定哪一个 action 执行时,将执行默认的 action。缺省情况下,默认的 action
名为
index
。可以通过设置
CController::defaultAction
改变默认的 action。
下边是最小的控制器类。因此控制器未定义任何 action,请求时会抛出异常。
class SiteController extends CController
{
}
路由(Route)
控制器和 actions 通过 ID 标识的。控制器 ID 的格式:
path/to/xyz
对应的类文件
protected/controllers/path/to/XyzController.php
, 相应的
xyz
应该用实际的控制器名替换 (例如
post
对应
protected/controllers/PostController.php
). Action ID 与
action
前辍构成 action
method。例如,控制器类包含一个
actionEdit
方法, 对应的 action ID 就是
edit
。
注意: 在 1.0.3 版本之前, 控制器 ID 的格式是
path.to.xyz
而不是
path/to/xyz
。
Users request for a particular controller and action in terms of route. A route is formed by concatenating a controller
ID and an action ID separated by a slash. For example, the route
post/edit
refers to
PostController
and its
edit
action. And by default, the URL
http://hostname/index.php?r=post/edit
would request for this
controller and action.
注意: By default, routes are case-sensitive. Since version 1.0.1, it is possible to make routes case-insensitive by
setting
CUrlManager::caseSensitive
to be false in the application configuration. When in case-insensitive
mode, make sure you follow the convention that directories containing controller class files are in lower case, and
both
controller map
and
action map
are using keys in lower case.
Since version 1.0.3, an application can contain
modules
. The route for a controller action inside a module is in the
format of
moduleID/controllerID/actionID
. For more details, see the
section about modules
.
控制器实例化
CWebApplication
在处理一个新请求时,实例化一个控制器。程序通过控制器的ID,并按如下规则确定控制器类
及控制器类所在位置
If
CWebApplication::catchAllRequest
is specified, a controller will be created based on this property,
and the user-specified controller ID will be ignored. This is mainly used to put the application under
maintenance mode and display a static notice page.
If the ID is found in
CWebApplication::controllerMap
, the corresponding controller configuration will
be used to create the controller instance.