YII2.0 开发基础学习笔记(二)

4.Yii2的Request Html组件

Request组件

Request 封装了$_SERVER ,统一了不同Web服务器的变量, 并且提供 $_POST,$_GET,$_COOKIES ,还包括HTTP中PUT、DELETE 等方法。

Request组件的调用

1) 直接调用Request类: \Yii::$app->request

2) 常用Request方法及属性

  • 判断是不是Ajax请求:\Yii::$app->request->isAjax
var_dump(\Yii::$app->request->isAjax);
  • 判断是不是Post请求:\Yii::$app->request->isPost
var_dump(\Yii::$app->request->isPost);
  • 获取用户浏览器:\Yii::$app->request->userAgent
echo \Yii::$app->request->userAgent,'<br />';
  • 获取用户IP:\Yii::$app->request->userIp
echo \Yii::$app->request->userIp,'<br />';
  • 读取$_GET 全部数据:\Yii::$app->request->get()
print_r(\Yii::$app->request->get());
print_r($_GET);
  • 读取$_GET 数据:\Yii::$app->request->get(‘username’)
echo \Yii::$app->request->get('r'),'<br />';
  • 读取$_POST 全部数据:\Yii::$app->request->post()
print_r(\Yii::$app->request->post());
print_r($_POST);
  • 读取$_POST 数据:\Yii::$app->request->post('username')
echo \Yii::$app->request->post('r'),'<br />';

更多的信息可以查阅:http://www.yiiframework.com/doc-2.0/yii-web-request.html

HTML组件

\yii\helpers\Html组件,提供了封装好的Html代码,直接调用Html 的相对方法就可以生成相对应的html代码。

<?=?>
<?php echo?>

调用HTML组件:

<?php
    use yii\helpers\Html;
?>

调用常用的HTML组件之直接生成HTML

1) 生成表单

//beginForm(提交的Url','类型POST或GET','表单的属性id,class 等')
<?=\yii\helpers\Html::beginForm('' , 'post' , ['id' => 'addForm']);?>

//endForm 也是必须,就是闭合表单
<?=\yii\helpers\Html::endForm();?>

2) 生成Text输入框

//input("类型text/password/text",'name 的名称','默认值' , '属性例如class,id 等');

<?=\yii\helpers\Html::input('text' , ‘name’, '' , ['class'=>'name' , 'id' => 'name']);?>
//直接生成指定类型的typeInput('name 的名称','默认值', '属性例如class,id 等')

//直接生成password 类型的输入框
<?=\yii\helpers\Html::passwordInput('pwd' , '' , ['id' => 'password'])?>

//直接生成text 类型的输入框
<?=\yii\helpers\Html::textInput("name" , '' , ['id' => 'name'])?>

//直接生成hidden 类型的隐藏框
<?=\yii\helpers\Html::hiddenInput("hidden" , '' , ['id' => 'hidden'])?>

3) 生成textArea

//textarea('name 的名称','默认值','属性例如class,id 等')

<?=\yii\helpers\Html::textarea('intro' , '' , ['class'=>'intro' ]);?>

4) 生成radio及radio列表

//radio('name 的名称' , '是否选中true/false' , '属性例如class,id 等')

<?=\yii\helpers\Html::radio('status' , false , ['class' =>'status'])?>

//radioList('name 的名称' ,'选中的值' , '数组选中键值', '属性例如class,id 等')

<?=\yii\helpers\Html::radioList('fav' , 1 , [1 => 'test' , 2 => 'mrs' ] , ['class'=>'fav-list'])?>

5) 生成checkbox 及checkbox 列表

//checkbox('name 的名称' , '是否选中true/false', '性例如class,id 等')
<?=\yii\helpers\Html::checkbox("ckbox" , false , ['class' => 'ckbox'])?>
//checkboxList('name 的名称' ,'选中的值', '数组选中键值' , '属性例如class,id 等')

<?=\yii\helpers\Html::checkboxList('cklist' , 1 , [1 => 'mr' , 2 => 's' ] , ['class'=>'cklist'])?>

6) 生成select 下拉框

//dropDownList('name 的名称' ,'选中的值' , '数组选中键值' , '属性例如class,id 等')

<?=\yii\helpers\Html::dropDownList('sts' , 0 , [1 => '是' , 0 => '否' ] , ['class'=>'sts'])?>

7) 生成label

//label('显示的名称' , 'for 的字段' , '属性例如class,id 等')

<?=\yii\helpers\Html::label('name:' , 'uname' , ['class'=>'label'])?>

8) 生成上传控件

//fileInput('name 的名称' , '默认值' , '属性例如class,id 等')
<?=\yii\helpers\Html::fileInput('image' , null , ['class'=>'upload' ])?>

9) 生成按钮

//button('显示的文字' , '属性例如class,id 等')

<?=\yii\helpers\Html::button("按钮" , ['class' => 'btn'])?>

<?=\yii\helpers\Html::submitButton("提交按钮" , ['class' => 'btn-submt'])?>

<?=\yii\helpers\Html::resetButton("重置" , ['class' => 'btn-reset'])?>

调用常用的Html组件之生成与Model字段关联的Html

1)生成Text输入框

//$model是实例化一个Model,title则是它的字段

//activeInput('input的类型text/password' , '实例化Model', '字段' , '属性例如class,id 等')

<?=\yii\helpers\Html::activeInput('title' , $model, 'title' , ['class' => ‘input'])?>
//直接生成指定类型的typeInput('实例化Model' , '字段' , '属性例如class,id 等')

<?=\yii\helpers\Html::activeTextInput($model, 'name' , ['class' => 'input'])?>

<?=\yii\helpers\Html::activePasswordInput($model, 'pwd' , ['class' => 'input'])?>

<?=\yii\helpers\Html::activeHiddenInput($model, 'name' , ['class' => 'input'])?>

2) 生成textArea

//activeTextarea('实例化Model', '字段' , '属性例如class,id 等')
<?=\yii\helpers\Html::activeTextarea($model , 'content' , ['class'=>'intro' ]);?>

3) 生成radio 及radio 列表

//activeRadio('实例化Model', '字段' , '属性例如class,id 等')
<?=\yii\helpers\Html::activeRadio($model , 'sts', ['class' =>'status'])?>
//activeRadioList('实例化Model', '字段', '数组(键值)' , '属性例如class,id 等')
<?=\yii\helpers\Html::activeRadioList($model,'sts' , [1=>'mrs' ,2=>'s' ] , ['class'=>'st'])?>

4) 生成checkbox及checkbox列表

//activeCheckbox('实例化Model', '字' , '属性例如class,id 等')

<?=\yii\helpers\Html::activeCheckbox($model , 'sts' , ['class' => 'ckbox'])?>

//activeCheckboxList('实例化Model’, '字段', '数组(键值)' , '属性例如class,id 等')

<?=\yii\helpers\Html::activeCheckboxList($model , 'sts',[1=>'f',2=>'m'], ['class'=>'ss'])?>

5) 生成select 下拉框

//activeDropDownList('实例化Model', '字段', '数组(键值)' , '属性例如class,id 等')
<?=\yii\helpers\Html::activeDropDownList($model,'fg',[1=>'f',2=>'m'] , ['class'=>'sx'])?>

6)html转义和反转义html代码

        $html = '<b>hello</b>';

        $html1 = \yii\helpers\Html::encode($html);
        echo $html1;

        $html2 = \yii\helpers\Html::decode($html1);
        echo $html2;

5.Yii2深入了解模型之模型验证

Model的load方法

load方法可以直接加载$_POST等数据,而POST的数据下标必须跟Model的类名一致的, 例如Article::load($_POST)等于加载$_POST['Article']里面的数据, 另外可以load的字段必须出现在rules方法的数组中,不然也无法直接赋值。

<?php
$model = new \app\models\Article;
$model -> load(\Yii::$app->request->post());
?>
    public function actionValidate(){

            $data = [
                    'Test' => [
                    'username' => 'story1',
                    'password' => '123456',
                    'repassword' => '123456',
                    'age' =>'5.1',
                    'number'=>'2',
                    'email'=>'123456@qq.com',
                    'sex' =>'nan',
                    'pt' =>'mrs56',
                    'str' =>'13',
                ]
            ];

            $test = new \app\models\Test();

            $test->load($data);

            if(!$test->validate()){
                    //获取错误
                    print_r($test->getErrors());
            }

            //var_dump($test);
    }

Model的rules验证规则

rules验证规则是Controller中model调用validate()的时候进行调用。

1) rules有22种验证规则

常用的有以下几种:

  • safe:不验证的字段

['字段','safe'], [['字段' , '字段'] , 'safe' ]

[['username','password'],'safe'],
  • required:不能为空,必须验证

['字段','required', 'message'=>'不能为空'], [['字段','字段'],多个字段可以是数组','required', 'message'=>'不能为空'],

[['username','password'],'required','message' => '不能为空!'],
  • compare:对比验证

['字段','compare', 'compareValue’' => '对比的值','message'=>'提示信息'], ['字段','compare', 'compareAttribute'=> '对比的字段','message'=>'提示信息'],

['password','compare','compareValue'=>'123456','message'=>'密码不是123456'],
['password','compare','compareAttribute'=>'repassword','message'=>'两次密码不一致!'],
  • double:双精度数字验证

['字段','double','min'=>'最小的值','max'=>'最大的值' , 'tooSmall' => '小于最小值的提 示','tooBig’ => ‘小于最大值的提示’ , ‘message’=>’必须是个数字’],

['age','double','min'=>'1.2','max'=>'10.5','tooSmall'=>'不能小于1.2','tooBig'=>'不能大于10.5','message'=>'不在规定的双精度范围内'],
  • Integer:整型数字验证

['字段','integer', 'message'=>'提示信息'],

['number','integer','min'=>'2','max'=>'8','tooSmall'=>'不能小于2','tooBig'=>'不能大于8','message'=>'不在整数规定的范围内'],
  • string:字符串验证

['字段','string', 'min' => '字符串最小长度' , 'max' => '字符串最大长度' , 'tooShort'=>'字符串过短提示' , 'tooLong' => '字符串过长提示'],

['str','string','min'=>'2','max'=>'10','tooShort'=>'不能小于10位','tooLong'=>'不能大于20位','message'=>'不在字符串规定的范围内'],
  • email:邮箱验证

['字段','email','message'=>'提示信息'],

['email','email','message'=>'邮箱的格式错误!'],
  • in:范围值验证
['字段','in', 'range' => '范围值', 'message'=>'提示信息'],
  • match:正则验证

['字段','in', ‘pattern' => '/正则/’, 'message'=>'提示信息'],

['pt','match','pattern'=>'/^mrs\d{2,}$/','message'=>'不符合mrs加2个数字开头!'],
  • unique:唯一验证 ['字段','unique','message'=>'提示信息'],
  • captcha:验证码验证 ['字段','captcha', 'captchaAction' => 'login/captcha','message'=>'提示信息'],

2) 自定义函数验证规则

['字段','自定函数' , 'params' => '传入自定义函数params的值'],

<?php
public function checkPassword($attribute , $params){//自定义函数
if(empty($this->$attribute)){
$this->addError($attribute , '不能为空');
  }
 }
?>

Model的getErrors()获取验证错误

当validate验证有错误时,可以用getErrors获取错误,也可以用getFirstError或getFirstErrors获取。

<?php
$model = new Article();
If(!$model -> validate()){
print_r($model->getErrors());
}
?>

Demo

Models\Test.php:

<?php
namespace app\models;
use yii\base\Model;

class Test extends Model{
    public $username;
    public $password;
    public $repassword;
    public $age;
    public $number;
    public $email;
    public $sex;
    public $pt;
    public $str;

    public function rules(){
        return[
                //['username','required','message' => '用户名不能为空!'],
                //['password','required','message' => '密码不能为空!'],

                [['username','password'],'required','message' => '不能为空!'],
                //['password','compare','compareValue'=>'123456','message'=>'密码不是123456'],
                ['password','compare','compareAttribute'=>'repassword','message'=>'两次密码不一致!'],
                ['repassword','safe'],

                ['age','double','min'=>'1.2','max'=>'10.5','tooSmall'=>'不能小于1.2','tooBig'=>'不能大于10.5','message'=>'不在规定的双精度范围内'],
                ['number','integer','min'=>'2','max'=>'8','tooSmall'=>'不能小于2','tooBig'=>'不能大于8','message'=>'不在整数规定的范围内'],
                ['email','email','message'=>'邮箱的格式错误!'],
                ['sex','in','range'=>['nan','nv'],'message'=>'不在选择范围内!'],

                ['pt','match','pattern'=>'/^mrs\d{2,}$/','message'=>'不符合mrs加2个数字开头!'],
                ['str','string','min'=>'2','max'=>'10','tooShort'=>'不能小于10位','tooLong'=>'不能大于20位','message'=>'不在字符串规定的范围内'],

                //['username','checkUsername'],
                ['username','checkUsername','params'=>['message'=>'不是等于story']],

                //[['username','password'],'safe'],
        ];
    }

    public function checkUsername($attribute,$params){
        //print_r($params);
        //echo $this->$attribute, '< br/>';

        if ($this->$attribute != 'story') {
            //$this->addError($attribute,'不等于story的用户名!');
            $this->addError($attribute,$params['message']);
        }
    }
}
?>

controllers\TestController.php:

<?php
namespace app\controllers;
use yii\web\Controller;

class TestController extends Controller{

    public function actionIndex(){
    }
    public function actionValidate(){

            $data = [
                    'Test' => [
                    'username' => 'story1',
                    'password' => '123456',
                    'repassword' => '123456',
                    'age' =>'5.1',
                    'number'=>'2',
                    'email'=>'123456@qq.com',
                    'sex' =>'nan',
                    'pt' =>'mrs56',
                    'str' =>'13',
                ]
            ];

            $test = new \app\models\Test();

            $test->load($data);

            if(!$test->validate()){
                    //获取错误
                    print_r($test->getErrors());
            }

            //var_dump($test);
    }
  }
?>

访问:

http://localhost:8080/index.php?r=test/validate

6.Yii2深入了解模型之增删改查

ActiveRecord 类型的增删改查

findAll查询多条数据

$articles = Article::findAll(['status' =>'1']);
//查询Article , status为1的所有数据

根据findOne进行查询

$article = Article::findOne(2);//直接根据id查询
$article = Article::findOne(['status'=>'1']);//根据指定条件查询

根据find()进行查询

$article = Article::find()->where(['id'=>'1'])->one();
$article = Article::find()->where('id=2')->one();
$article = Article::find()->where('id=:id',[':id'=>2])->one();
//查询一条id等于1的数据

$article = Article::find()->where(['status'=>'1'])->all();
$article = Article::find()->where('status=:status',[':status' => '1']) -> all();
//查询status等于1的所有数据

$article = Article::find()->where(['status'=>'1'])->orderBy('date ASC')->all();
//查询status等于1的所有数据, 根据date排序

$article = Article::find()->where(['status'=>'1'])->limit(1)->all();
//查询status等于1的所有数据, 读取第1条

$article = Article::find()->where(['status'=>'1'])->orderBy('date ASC')->offset(5)->limit(3)->all();
//查询status等于1的数据, 根据date排序,从第5条开始,读取3条

更新一条数据

$article = Article::findOne(1);
$article -> title = 'This is a new title';
var_dump($article->save(false));
//save 函数第一个参数默认为true , 就是更新或插入启动验证。如果不想使用验证可以用save(false);

更新指定属性

updateAll('更新的属性','条件')

var_dump(Article::updateAll(['title' =>'222update'],['id'=>'1']));

添加一条新数据

$article = new Article();
$article -> title = 'new new new title';
$article -> description = 'new description,new description';
$article -> content = 'new content,new content';
var_dump($article->save(false));

删除一条数据

var_dump(Article::findOne(3)->delete());

删除指定条件的数据

var_dump(Article::deleteAll(['id'=>5]));

\yii\db\Query 查询数据

$db = new \yii\db\Query;
$article = $db -> select('id') -> from('mrs_article') -> where('id=:id',[':id'=>1]) -> one();
//查询一条id等于1的数据

$article = $db -> select('id') -> from('mrs_article') -> where('status=:status',[':status' => 2]) -> all();
//查询多条id等于2的数据

$db->select('id')->from('mrs_article')->where(['id' =>[1,2]])->all();
//in查询多条

$db->select('id')->from('mrs_article')->orderBy('date DESC')->offset(5)->limit(3)->all();
//根据时间排序,并且从第5条开始获取3条


$article = $db -> select('id') -> from('mrs_article') -> where('status=:status',[':status' => 2]) -> orderBy('id DESC')-> all();

$article = $db -> select('id') -> from('mrs_article') -> where('status=:status',[':status' => 2]) -> orderBy('id DESC') -> offset(1) -> limit(1) -> all();
//多条件的查询


$db->select('id')->from('mrs_article')->count();
//查询数据总个数


echo Article::find()->count();
//find数据库中的数据总条数

var_dump($article);

Yii::$app->db 进行增删改查

查询数据

$db = \Yii::$app -> db;
$article = $db -> createCommand("SELECT * FROM ".$db->tablePrefix."article") -> queryAll();
//查询所有数据

$article = $db -> createCommand("SELECT * FROM ".$db->tablePrefix."article") -> queryOne();
//查询一条数据

$article = $db -> createCommand("SELECT * FROM ".$db->tablePrefix."article WHRER id=:id")->bindValue(':id','1') -> queryOne();
//绑定单个防注入参数

$article = $db -> createCommand("SELECT * FROM ".$db->tablePrefix."article WHERE id=:id AND status=:status")->bindValues([':id' => '2',':status' =>'1'])->queryOne();
//绑定多个防注入参数

$article = $db -> createCommand("SELECT COUNT(*) FROM".$db->tablePrefix."article")->queryScalar();
//查询指定字段的数据个数

更新数据

$a = $db -> createCommand()->insert($db->tablePrefix."article",['title' => 'aaaa','description' => 'bbbbb'])->execute();

插入数据

var_dump($db->createCommand()->update($db->tablePrefix."article",['title' => 'cccccc'],'id=:id',[':id' => '7'])->execute());

###删除数据

var_dump($db->createCommand()->delete($db->tablePrefix."article" , 'id=:id' , [':id' => 7])->execute());

Demo

models\Article.php

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Article extends ActiveRecord{
    public static function tableName(){
        return '{{%article}}';
    }
}
?>

controllers\TestController.php:

<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\Article;

class TestController extends Controller{

    public function actionIndex(){
    }
    public function actionDb(){
       $articles = Article::findAll(['status' =>'1']);
       print_r($articles);
    }
  }
?>

访问:

http://localhost:8080/index.php?r=test/db

7.Yii2小实战前知识点补漏

1) \yii\helpers\Html::error()

\yii\helpers\Html::error()可以直接打印关联数据库的错误

$test = new \app\models\Test;
$test -> validate();
echo \yii\helpers\Html::error($test,'username',['class'=>'error']);

2) \yii\helpers\Url 组件

http://localhost:8080/yii2-demo/web/index.php?r=article/index 为例:

echo \yii\helpers\Url::base();
//base输出根目录,输出/yii2-demo/web



echo \yii\helpers\Url::base(true);
//输出http://localhost:8080/yii2-demo/web



//home 是输出首页, 加上true是输出加域名的首页
echo \yii\helpers\Url::home();
//输出/yii2-demo/web/index.php



echo \yii\helpers\Url::home(true);
//输出http://localhost:8080/yii2-demo/web/index.php



echo \yii\helpers\Url::current();
//当前的Url,输出/yii2-demo/web/index.php?r=article/index



//to 和toRoute都是生成Url , 后面加true都是生成带域名的Url



echo \yii\helpers\Url::to(['article/add']);
//输出/yii2-demo/web/index.php?r=article/add



echo \yii\helpers\Url::to(['article/edit' , 'id' => 1]);
//输出/yii2-demo/web/index.php?r=article/add&id=1



echo \yii\helpers\Url::to(['article/add'] , true);
//输出http://localhost:8080/yii2-demo/web/index.php?r=article/add


echo \yii\helpers\Url::to(['article/edit' , 'id' => 1] , true);
//输出http://localhost:8080/yii2-demo/web/index.php?r=article/add&id=1


echo \yii\helpers\Url::toRoute(['article/add']);
//输出/yii2-demo/web/index.php?r=article/add



echo \yii\helpers\Url::toRoute(['article/edit' , 'id' => 1]);
//输出/yii2-demo/web/index.php?r=article/add&id=1



echo \yii\helpers\Url::toRoute(['article/add'] , true);
//输出http://localhost:8080/yii2-demo/web/index.php?r=article/add



echo \yii\helpers\Url::toRoute(['article/edit' , 'id' => 1] , true);
//输出http://localhost:8080/yii2-demo/web/index.php?r=article/add&id=1



//to 和toRoute 之间的区别, 传入string 时, to会直接把string当成url 和toRoute则会解析:



echo \yii\helpers\Url::to('article/add');
//输出article/add



echo \yii\helpers\Url::toRoute('article/add');
//输出/yii2-demo/web/index.php?r=article/add

更加具体的请查阅:http://www.yiiframework.com/doc-2.0/yii-helpers-url.html

3) 分页组件

分页组件是由\yii\data\Pagination提供的, 而在view 中可以直接调用 \yii\widgets\LinkPager 直接生成分页的html.

<?php
//totalCount是总数量,pageSize则是每页显示的个数
$pagination = \yii\data\Pagination(['totalCount'=>100 , 'pageSize' => 10]);

//分页的偏移量
echo $pagination->offset;

//每页读取的个数
echo $pagination->limit;

//生成分页html 代码
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination, //分页类
'options' => [ //设置html 属性
'id' => 'page'
     ],
  ]);
?>
$pagination = new \yii\data\pagination(['totalCount' => 100,'pageSize' => 5]);

echo \yii\widgets\LinkPager::widget([
            'pagination' => $pagination,
            'options' => [
               'id' => 'page'
                ],
            ]);

更多详细的请查阅:

Pagination 类:http://www.yiiframework.com/doc-2.0/yii-data-pagination.html

LinkPager 类:http://www.yiiframework.com/doc-2.0/yii-widgets-linkpager.html

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

标签:

分享到:

扫一扫在手机阅读

扫一扫 在手机阅读、分享本文

上一篇: 下一篇:

精彩评论

全部回复2人评论705 views人参与
  1. 1楼
    discount cialis

    I am not sure where you are getting your info, however good topic.
    I needs to spend some time studying much more or working out more.

    Thanks for excellent info I was searching for this information for my mission.

    2018-05-01 03:26:15 回复
  2. 2楼
    cheapest cialis 20mg

    Heya i’m for the first time here. I found this board and I to find
    It really useful & it helped me out much. I’m hoping to offer something again and aid others such as you
    aided me.

    2018-05-28 05:20:52 回复

电子邮件地址不会被公开。 必填项已用*标注

loading

孤独的渔夫,自闭修炼到白头~

最新评论