小兔网

yii控制器怎么定义

控制器是 MVC 模式中的一部分, 是继承yii\base\Controller类的对象,负责处理请求和生成响应。具体来说,控制器从应用主体接管控制后会分析请求数据并传送到模型, 传送模型结果到视图,最后生成输出响应信息。 (推荐学习:yii框架

动作

控制器由 操作 组成,它是执行终端用户请求的最基础的单元, 一个控制器可有一个或多个操作。

如下示例显示包含两个动作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控制器怎么定义的知识。速戳>>知识兔学习精品课!