一、目录结构:
模型类:models/
视图文件:views/
二、MVC示例:
在controllers下的SiteController.php里新增方法:
//action后面的操作映射为say-hello
public function actionSayHello($message='World'){
return $this->render('say',['message'=>$message]);
}
在views/site下新建视图say.php,内容:
=Html::encode($message)?>
查看输出结果
三、Form示例
修改SiteControlloer.php:
[
'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();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
//action后面的操作映射为say-hello
public function actionSayHello($message='World'){
return $this->render('say',['message'=>$message]);
}
public function actionEntry(){
$model=new EntryForm;
if($model->load(Yii::$app->request->post()) && $model->validate()){
return $this->render('entry-confirm',['model'=>$model]);
}else
{
return $this->render('entry',['model'=>$model]);
}
}
}
= $form->field($model,'name')?>
= $form->field($model,'email')?>
=Html::submitButton('Submit',['class'=>'btn btn-primary'])?>
新增视图entry-confirm.php:
You have entered the following information:
- := Html::encode($model->name)?>
- :=Html::encode($model->email)?>
现在目录结构是这样的: