一、Yii框架介绍
Yes it is! 一个高性能、基于组件的php框架。
使用mvc模式
纯面向对象
支持restful开发
支持多级缓存
具有ActiveRecord
高性能、可重用、简洁优雅
二、MVC模式
三、安装
1.使用composer安装
2.直接下载yii框架包,需要手动修改配置文件web.php 添加cookieValidationKey
四、SayHello
1.构造请求路径
//127.0.0.1/basic/web/index.php?r=comment/say
comment:控制器id
say:操作id
2.构造控制器
服务器controllers目录中需要创建CommentController控制器,并添加actionSay方法
<?php
namespace app\controllers;
use yii\web\controller;
// controllers/CommentController.php
Class CommentController extends Controller
{
public function actionSay(){
return $this->render('say', ['message'=>"say hello"]);
}
}
?>
3.返回页面视图
服务器views目录中需要创建comment目录,comment目录中创建要返回的视图say.php
<?php
// views/say.php
use yii\helpers\Html;
?>
<?= Html::encode($message)?>
五、Form
1.构建model对象 FormModel.php
Model类与数据库表无关。
<?php
namespace app\models;
use yii\base\model;
Class FormModel extends Model
{
public $name;
public $email;
// 配置校验规则
public function rules(){
return [
[['name', 'email'],'required'],
['email', 'email']
];
}
}
?>
2.使用Yii组件构建页面form
yii\widgets\ActiveForm部件可以生成html表单
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
// views\model\form.php
?>
<?php $form =ActiveForm::begin(); ?>
<?= $form->field($model, 'name')?>
<?= $form->field($model, 'email')?>
<div>
<?= Html::submitButton('Submit')?>
</div>
<?php ActiveForm::end(); ?>
<?php
// views\model\form-show.php
?>
<li><?= $model->name?></li>
<li><?= $model->email?></li>
3.创建控制器ModelController和操作actionForm
<?php
namespace app\controllers;
use Yii;
use yii\web\controller;
use app\models\FormModel;
// controllers\ModelController.php
Class ModelController extends Controller
{
public function actionForm(){
$model = new FormModel();
if($model->load(Yii::$app->request->post()) && $model->validate()){
return $this->render('form-show', ['model'=>$model]);
}
return $this->render('form', ['model'=>$model]);
}
}
?>
4.测试url
//localhost/basic/web/index.php?r=model/form
六、使用DataBase
1.创建ActiveRecord对象,该对象与数据表关联,同时封装了一些基本的CRUD操作
<?php
namespace app\models;
use yii\db\ActiveRecord;
Class UserInfo extends ActiveRecord
{
public static function tableName(){
return "user_info";
}
}
?>
2.创建DbController和actionList
<?php
namespace app\controllers;
use yii\web\controller;
use app\models\UserInfo;
use yii\data\Pagination;
Class DbController extends Controller{
public function actionList(){
$query = UserInfo::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count()
]);
$users = $query->orderBy('sex')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('user-list', ['users'=>$users, 'pagination'=>$pagination]);
}
}
?>
3.创建列表视图,使用分页组件
<?php
use yii\widgets\LinkPager;
?>
<ul>
<?php foreach($users as $user): ?>
<li>
<?= $user->sex ?>
</li>
<?php endforeach; ?>
</ul>
<?= LinkPager::widget(['pagination'=>$pagination])?>
4.请求url
//localhost/basic/web/index.php?r=db/list
参考资料:
php框架学习网