Yii 控制器
控制器负责处理请求并生成响应。用户请求后,控制器将分析请求数据,将它们传递给模型,然后将模型结果插入到视图中,并生成响应。
了解操作
控制器包括操作。它们是用户可以请求执行的基本单位。控制器可以有一个或多个动作。
让我们看看基本应用程序模板的 SiteController -
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class SiteController extends Controller {
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex() {
return $this->render('index');
}
public function actionLogin() {
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
public function actionLogout() {
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact() {
//load ContactForm model
$model = new ContactForm();
//if there was a POST request, then try to load POST data into a model
if ($model->load(Yii::$app->request->post()) && $model>contact(Yii::$app->params
['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
public function actionAbout() {
return $this->render('about');
}
public function actionSpeak($message = "default message") {
return $this->render("speak",['message' => $message]);
}
}
?>
使用PHP内置服务器运行基本应用程序模板,然后转到 http:// localhost:8080 / index.php?r = site / contact 的Web浏览器。你会看到下面的页面 -

当您打开此页面时,将执行 SiteController 的联系动作。代码首先加载 ContactForm 模型。然后呈现联系人视图并将模型传递给它。

如果你填写表格并点击提交按钮,你会看到以下内容 -

注意,这次执行下面的代码 -
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app>params ['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
如果有POST请求,我们将POST数据分配给模型并尝试发送电子邮件。如果我们成功了,我们会设置一个闪光消息,其中包含文字“感谢您与我们联系。我们会尽快回复您。“并刷新页面。
了解路线
在上面的示例中,在URL中, http:// localhost:8080 / index.php?r =站点/联系人, 路由是 站点/联系人 。 SiteController中 的联系动作( actionContact )将被执行。 **
路线由以下部分组成 -
- moduleID - 如果控制器属于一个模块,则存在这部分路由。
- controllerID (上例中的站点) - 在同一模块或应用程序中的所有控制器中标识控制器的唯一字符串。
- actionID (在上面的示例中为联系人) - 一个唯一的字符串,用于标识同一控制器内所有操作之间的操作。
路由的格式是 controllerID / actionID 。如果控制器属于一个模块,则它具有以下格式: moduleID / controllerID / actionID 。
下一章:Yii 使用控制器
Web应用程序中的控制器应该从 yii \ web \ Controller 或其子类 继承 。在控制台应用程序中,它们应该从yii \ console \ Controller或其子类继承。让我们在 controlle ...
AI 中文社