动作
控制器由 操作 组成,它是执行终端用户请求的最基础的单元, 一个控制器可有一个或多个操作。
如下示例显示包含两个动作view and create 的控制器post:
namespace app\controllers;use yii;use app\models\post;use yii\web\controller;use yii\web\notfoundhttpexception;class postcontroller extends controller{ public function actionview($id) { $model = post::findone($id); if ($model === null) { throw new notfoundhttpexception; } return $this->render('view', [ 'model' => $model, ]); } public function actioncreate() { $model = new post; if ($model->load(yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } }}
创建控制器
在web applications网页应用中,控制器应继承yii\web\controller 或它的子类。 同理在console applications控制台应用中,控制器继承yii\console\controller 或它的子类。
如下代码定义一个 site 控制器:
namespace app\controllers;use yii\web\controller;class sitecontroller extends controller{}
以上就是yii控制器怎么定义的详细内容。