了解操作
控制器包括操作。它们是用户可以请求执行的基本单元。一个控制器可以有一个或多个动作。
让我们看一下基本应用程序模板的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 数据分配给模型并尝试发送电子邮件。如果我们成功了,我们会设置一条带有文本“感谢您与我们联系”的 Flash 消息。我们会尽快回复您。” 并刷新页面。