class PostController extends CController
{
public function actionCreate()
{
if(isset($_GET['category']))
$category=(int)$_GET['category'];
else
throw new CHttpException(404,'invalid request');
// ... fun code starts here ...
}
}
现在使用动作参数功能,我们可以更轻松的完成任务:
class PostController extends CController
{
public function actionCreate($category, $language='en')
{
$category = (int)$category;
echo 'Category:'.$category.'/Language:'.$language;
// ... fun code starts here ...
}
}
注意我们在动作方法 actionCreate 中添加了两个参数。这些参数的名字必须和我们想要从 $_GET 中提取的名字一致。当用户没有在请求中指定 $language 参数时,这个参数会使用默认值 en 。由于 $category 没有默认值,如果用户没有在 $_GET 中提供 category 参数,将会自动抛出一个 CHttpException (错误代码 400) 异常。
从版本1.1.5开始,Yii已经支持数组的动作参数。使用方法如下:
class PostController extends CController
{
public function actionCreate(array $categories)
{
// Yii will make sure $categories be an array
}
} 控制器生命周期
处理一个请求时,应用主体 会根据请求路由创建一个控制器,控制器经过以下生命周期来完成请求: