Yii2速查手册

2018-12-26  本文已影响0人  Chting

Controller控制器常用方法

  1. 重定向 $this->redirect([‘test/index’])
  2. 回到首页 $this->goHome()
  3. 返回 $this->goBack()
  4. 刷新当前页面 $this->refresh()
  5. 渲染视图 $this->render(视图,注入视图数组数据)
  6. 渲染没有layout的视图 $this->renderPartial(视图,注入视图数组数据)
  7. 响应Ajax请求,layout的视图 $this->renderAjax(视图,注入视图数组数据)修改Test控制器的index操作

Request组件常用方法

  1. request对象 \Yii::$app->request
  2. 判断Ajax请求 \Yii::$app->request->isAjax
  3. 判断POST请求 \Yii::$app->request->isPost
  4. 获取浏览器信息 \Yii::$app->request->userAgent
  5. 获取客户端IP \Yii::$app->request->userIp
  6. 读取所有get数据 \Yii::$app->request->get()
  7. 读取单个get数据 \Yii::$app->request->get('r')
  8. 读取所有post数据 \Yii::$app->request->post()
  9. 读取单个post数据 \Yii::$app->request->get('post')
  10. 获取不包含host info的url部分 \yii::$app->request->url
  11. 获取整个URL \Yii::$app->request->absoluteUrl
  12. 获取host info部分 \Yii::$app->request->hostInfo;
  13. 入口脚本之后查询字符串之前 \Yii::$app->request->pathInfo
  14. 查询字符串 \Yii::$app->request->queryString
  15. host info之后,入口脚本之前部分 \Yii::$app->request->baseUrl;

Html助手常用方法

<?php //【一】表单:Html::beginForm(提交地址,提交方法,属性数组);?>
 
 
<?=Html::beginForm('','post',['id'=>'form','class'=>'form','data'=>'myself']);?>
 
 
    <?php //【二】输入框:Html::input(类型,name值,默认值,属性数组);?>
 
 
    <?=Html::input('text','test','',['class' => 'form-control','placeholder'=>'hehe']);?>
    <?=Html::input('email','email','admin@admin.com',['class' => 'form-control']);?>
    <?=Html::input('password','pwd','',['class' => 'form-control']);?>
    <?=Html::input('hidden','hidden','',['class' => 'form-control']);?>
 
 
    <hr />
    <?php //Html::表单类型Input(name值,默认值,属性数组);?>
 
 
    <?=Html::textInput('test','hehe',['class' => 'form-control']);?>
    <?=Html::textInput('email','admin@admin.com',['class' => 'form-control']);?>
    <?=Html::passwordInput('pwd','',['class' => 'form-control']);?>
    <?=Html::hiddenInput('hidden','',['class' => 'form-control']);?>
 
 
    <hr />
    <?php //【三】文本域:Html::textarea(表单name,默认值,属性数组);?>
    <?=Html::textarea('area','',['class'=>'form-control','rows'=>'3']);?>
 
 
    <hr />
    <?php //【四】单选按钮:Html::radio(name值,是否选中,属性数组);?>
    <?=Html::radio('sex',true,['calss'=>'form-control']);?>
    <?php //单选按钮列表:Html:;radioList(name值,选中的值,键值对列表,属性数组); ?>
    <?=Html::radioList('height','1',['1'=>'160','2'=>'170','3'=>'180'],['class'=>'form-control']);?>
 
 
    <hr />
    <?php //【五】复选框:Html::checkbox(name值,是否选中,属性数组);?>
    <?=Html::checkbox('haha',true,['calss'=>'form-control']);?>
    <?php //单选按钮列表:Html:;checkboxList(name值,选中的值,键值对列表,属性数组); ?>
    <?=Html::checkboxList('xixi','1',['1'=>'160','2'=>'170','3'=>'180'],['class'=>'form-control']);?>
 
 
    <hr />
    <?php //【六】下拉列表:Html:;dropDownList(name值,选中的值,键值对列表,属性数组); ?>
    <?=Html::dropDownList('list','2',['1'=>'160','2'=>'170','3'=>'180'],['class'=>'form-control']);?>
 
 
    <hr />
    <?php //【七】控制标签Label:Html::label(显示内容,for值,属性数组); ?>
    <?=Html::label('显示的','test',['style'=>'color:#ff0000']);?>
 
 
    <hr />
    <?php //【八】上传控件:Html::fileInput(name值,默认值,属性数组); ?>
    <?=Html::fileInput('img',null,['class'=>'btn btn-default']);?>
 
 
    <hr />
    <?php //【九】按钮:; ?>
    <?=Html::button('普通按钮',['class'=>'btn btn-primary']);?>
    <?=Html::submitButton('提交按钮',['class'=>'btn btn-primary']);?>
    <?=Html::resetButton('重置按钮',['class'=>'btn btn-primary']);?>
 
 
<?=Html::endForm();?>

CRUD常用方法
一、ActiveRecord活动记录的CURD
DQL

1. 查询所有
`Article::findAll(['status'=>1]);`
2.查询一条
`Article::findOne(1);                   //根据ID查询`
`Article::findOne(['status' => 1]);     //根据条件查询`
3.find()方法返回yii\db\ActiveQuery查询
`Article::find()->where(['id'=>1])->one();                          //ID等于1的一条数据`
`Article::find()->where(['status'=>1])->all();                      //状态等于1的所有数据`
`Article::find()->where('status=:status',[':status'=>1])->all();    //状态等于1的所有数据`
排序

//查询状态等于1的数据并根据pubdate排序
Article::find()->where(['status'=>1])->orderBy('pubdate DESC')->all();
 
 
//查询状态等于1的数据并根据pubdate排序,从第10条开始,取4条
Article::find()->where(['status'=>1])->orderBy('pubdate ASC')->offset(10)->limit(4)->all();
DML
save()方法
save第一个参数布尔值表示更新或插入时是否开启验证,默认为true

$article = Article::findOne(1);
$article->title = '更改测试1标题';
$article->save();
//更新-指定更新
Article::updateAll(['title'=>'测试1指定的跟新'],['id'=>1]);
 
 
//添加一条
$article = new Article();
$article->title = '测试添加标题1';
$article->content = '测试添加内容1';
$article->desc = '测试添加描述1';
$article->save();
 
 
//删除一条
Article::findOne(16)->delete();
 
 
//删除指定
Article::deleteAll(['id'=>16]);

二、查询构建器yii\db\Query

$db = new \yii\db\Query();
1.查询一条ID为2的数据
$db->select('id,title,content')->from('article')->where('id=:id',[':id'=>2])->one();
$db->select('id,title,content')->from('article')->where(['id'=>2])->one());
2.查询多条
$db->select('id,title,content')->from('article')->where(['status'=>1])->all();
$db->select('id,title,content')->from('article')->where(['id'=>[1,2]])->all()
3.根据pubdate排序,从第10条开始,取4条
$db->select('id,title,content')->from('article')->orderBy('pubdate DESC')->offset(10)->limit(4)->all();
4.统计查询
$db->select('id')->from('article')->count();

三、yii\db\Command
DQL

$db = \Yii::$app->db;
可通过$db->tablePrefix获取表前缀如果有的话


1.查询一条
$db->createCommand('SELECT * FROM `article`')->queryOne();
2.绑定单个防SQL注入参数
$db->createCommand('SELECT * FROM `article` WHERE id=:id')->bindValue(":id",2)->queryOne();
3.绑定多个防SQL注入参数
$db->createCommand('SELECT * FROM `article` WHERE id=:id AND status=:status')->bindValues([':id'=>1,':status'=>1])->queryOne();
4.查询多条
$db->createCommand('SELECT * FROM `article`')->queryAll();
5.统计查询
$db->createCommand('SELECT COUNT("id") FROM `article`')->queryScalar();

DML

1.更新数据
$db->createCommand()->update('`article`',['status'=>0],'id=:id',[':id'=>9])->execute();
2.插入数据
$db->createCommand()->insert('`article`',['title'=>'标题16','desc'=>'描述16','content'=>'内容16'])->execute();
3.一次插入多行
$db->createCommand()->batchInsert('`article`',['title','desc','content'],[
    ['17','17','17'],
    ['18','18','18'],
    ['19','19','19']
])->execute();
4.删除数据
$db->createCommand()->delete('`article`','status=0')->execute();

rule常用方法
模型的load方法
模型对象的load方法为模型加载数据,一般地,模型尝试从$_POST搜集用户提交的数据,由Yii的yii\web\Request::post()方法负责搜集。
另外load加载的字段必须在模型的rules方法里,不然也不能赋值。
模型的rules规则
常用验证规则:


1.【safe     不验证规则】
//['字段','safe']
//[['字段1','字段2',……],'safe']
2.【required 不能为空,必须验证】
//['字段','required','message' => '提示信息']
//[['字段1','字段2',……],'required','message' => '提示信息']
3.【compare  对比验证】
//['字段','compare','compareValue'=>'对比的值','message' => '提示信息']
//['字段','compare','compareAttribute'=>'对比的字段','message' => '提示信息']
4.【double   双精度数字验证】
//['字段','double','min'=>'最小值','max' => '最大值','tooSmall'=>'小于最小值提示','tooBig'=>'大于最大值提示','message'=>'提示信息']
5.【email    邮箱规则验证】
//['字段','email','message' => '提示信息']
6.【in       范围验证】
//['字段','in','range'=>['1','2','3',……],'message' => '提示信息']
7.【integer  整型数字验证】
//['字段','integer','message' => '提示信息']
8.【match    正则验证】
//['字段','match','parttern'=>'#正则#','message' => '提示信息']
9.【string   字符串验证】
//['字段','string','min'=>'最小长度','max' => '最大长度','tooShort'=>'小于最小长度提示','tooLong'=>'大于最大长度提示','message'=>'提示信息']
10.【unique  唯一验证】
//['字段','unique','message' => '提示信息']
11.【captcha 验证码验证】
//['字段','captcha','captchaAction',=>'login/captcha','message' => '提示信息']
12.自定义验证
//['字段','自定义方法']
//可通过在自定义方法里调用addError()来定义错误
例:
['username',function($attribute,$params){
    if(满足条件){
        $this->addError($attribute,'提示信息');
    }    
},'params'=>['message'=>'dd']]
 

更多类型参考类文档 http://www.yiichina.com/doc/api/2.0/yii-validators-validator
cookie和session
一、Cookie
Yii2的cookie主要通过yii\web\Request和yii\web\Response来操作的。

通过\Yii::app->response->getCookies()->add($cookie)来添加cookie。
通过\Yii::app->request->cookies读取cookie
添加一个cookie
方法一:
$cookie = new \yii\web\Cookie();
$cookie->name = 'name';                //cookie名
$cookie->value = 'value';              //cookie值
$cookie->expire = time() * 3600;       //过期时间
$cookie->httpOnly = true;              //是否只读
\Yii::$app->response->getCookies()->add($cookie);
方法二:
$cookie = new \yii\web\Cookie([
        'name' => 'name',
        'value' => 'value',
    'expire' => time() + 18000,
    'httpOnly' => true
]);
\Yii::$app->response->getCookies()->add($cookie);  
读取一个Cookie
$cookie = \Yii::$app->request->cookies;
$cookie->has('name');           //判断cookie是否存在
$cookie->get('name');           //get()方法读取cookie
$cookie->getValue('name');      //getValue()方法读取cookie
$cookie->count();           //获取cookie个数
$cookie->getCount();            //获取cookie个数  
删除一个Cookie
$name = \Yii::$app->request->cookies->get('name');
\Yii::$app->response->getCookies()->remove($name);  
删除全部Cookie
\Yii::$app->response->getCookies()->removeAll();

二、Session
yii2的session通过yii\web\Session实例的session应用组件来访问。

SESSION

$session = \Yii::$app->session;
添加一个session
$session->set('name_string','value');
$session->set('name_array',[1,2,3]);  
读取一个session
$session->get('name_string');
$session->get('name_array');  
删除一个session
$session->remove('name_array');  
删除所有session
$session->removeAll();

Url助手与分页组件常用
一些方法

Test控制器下新建一个actionUrl操作用来测试:
//不带域名根目录
//echo Url::base();
 
//带域名的根目录
//echo Url::base(true);
 
//不带域名的首页
//echo Url::home();
 
//带域名的首页
//echo Url::home(true);
 
//当前url
//echo Url::current();
Url::to()和Url::toRoute()
//Url::to和Url::toRoute都是生成Url,to的第一参数需要是数组,否则会被当做url
//第二个参数都是生成带域名的url
//没有传控制器默认为当前控制器
echo Url::to(['site/index'])."<br />";
echo Url::to(['site/index'],true)."<br />";
echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name'])."<br />";
echo Url::to(['@app', 'id' => 100])."<br />";
 
echo '<hr />';
echo Url::toRoute(['site/index'])."<br />";
echo Url::toRoute(['site/index'],true)."<br />";
Url::remember()记住当前url

分页组件
我们往article表中多插入一些数据:

INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题3','测试描述3','测试内容3');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题4','测试描述4','测试内容4');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题5','测试描述5','测试内容5');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题6','测试描述6','测试内容6');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题7','测试描述7','测试内容7');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题8','测试描述8','测试内容8');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题9','测试描述9','测试内容9');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题10','测试描述10','测试内容10');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题11','测试描述11','测试内容11');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题12','测试描述12','测试内容12');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题13','测试描述13','测试内容13');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题14','测试描述14','测试内容14');
INSERT  INTO `yii2basic`.`article`(`title`,`desc`,`content`) VALUES('测试标题15','测试描述15','测试内容15');

在actionUrl操作中通过DB查询和\yii\data\Pagination组织分页信息:

//AR构建DB查询
$article = Article::find();
$articleCount = clone $article;
$pageSize = 5;
 
$pages = new \yii\data\Pagination([
    'totalCount'=>$articleCount->count(),
    'pageSize'=>$pageSize
]);
 
$models = $article->offset($pages->offset)
    ->limit($pages->limit)
    ->all();
        
return $this->render('url',[
    'models' => $models,
    'pages'  => $pages
]);
在@app\views\test目录下新建url.php:
<?php
    use yii\widgets\LinkPager;
?>
 
<section>
    <?php
        //获取数据
        foreach($models as $model){
            echo $model->title;
        }
 
    ?>
</section>
 
<?=LinkPager::widget([
    'pagination'=>$pages,
    'options'=>[
        'class' => 'pagination'
    ]
]);?>
得到结果 image.png

原文

上一篇下一篇

猜你喜欢

热点阅读