• yii框架小技巧总结


    1、yii默认返回的数据结构

    在用yii框架进行开发的时候,如果纯做api接口,那么需要    throw new NotFoundHttpException() 时自动返回json格式,那么需要在config下的web.php中做好下的配置

    'components' => [
        ...
        'response' => [ 'format' => YII_ENV_DEV ? yiiwebResponse::FORMAT_HTML: yiiwebResponse::FORMAT_JSON ],
        ...
    ]

    2、yii中配置默认的主页

    在yii框架开发中,配置默认的主页,需要在config/web.php中配置一条信息

    'defaultRoute' => 'site/index',

    3、yii中进行redis配置的时候,注意按下面的配置

    'redis' => [
        'class' => 'yii
    edisconnection',
        'hostname' => '127.0.0.1',      //注意:这里不要配置localhost
        'port' => 6379,
        'database' => 0,
    ],

    如果hostname配置成localhost,那么用调用的时候,速度会比较慢

    4、yii中web配置中的user配置

    在yii中web配置中user所对应的配置项,相当于yiiwebUser这个类里的public公有项,在进行配置的时候,可以参考着配置,比如更改默认的登录地址与过期时间,如下:

    'user' => [
        'identityClass' => 'appmodelsUser',
        'enableAutoLogin' => true,
        'loginUrl' => ['site/login']
    ]

    5、yii中contoller类中actions方法的使用

    定义一个action类,注意需要继承yiiaseAction这个类

    <?php
     
    namespace appcommon;
     
    use yiiaseAction;
     
    //我们需要继承yiiaseAction类
    class TestAction extends Action {
     
        //这里的参数值是通过控制器actions中配置过来的
        public $data;
     
        //实现run方法
        public function run() {
            echo "这个是传入的参数{$this->data}"
        }
    }

    使用这个方法如下:

    <?php
     
    namespace appcontrollers;
     
    use YII;
    use yiiwebController;
     
    class IndexController extends Controller
    {
        //actions的作用主要是共用功能相同的方法
        public function actions()
        {
            return [
                'test' => [
                    'class' => 'appcommonTestAction',
                    'data' => 'this is test data'
                ],
            ];
        }
    }

    这样我们在地址栏就可以通过/index/test来访问调用了。

     6、yii中常用的rules的规则

    去除首尾空白字符

    ['email', 'trim'] 或 ['email', 'filter', 'filter' => 'trim']

    字段必填

    ['email', 'required']

    赋予默认值

    ['age', 'default', 'value' => 20]

    字符串长度

    ['email', 'string', 'min' => 3, 'max' => 20] 或 ['email', 'string', 'length' => [3, 20]]

    格式类型验证

    ['age', 'integer'] // 整数格式
    ['salary', 'double'] // 浮点数格式
    ['temperature', 'number'] // 数字格式
    ['isAdmin', 'boolean'] // 布尔格式
    ['email', 'email'] // email格式
    ['birthday', 'date'] // 日期格式
    ['website', 'url', 'defaultScheme' => 'http'] // URL格式

    验证码

    ['verificationCode', 'captcha']

    值在数据表中是唯一的

    ['email', 'unique', 'targetClass' => 'commonmodelsUsers']

    注意:这里的'targetClass' => 'appmodelsCommonModelsUsers‘进行指定;

    值在数据表中已存在

    ['email', 'exist', 'targetClass' => 'commonmodelsUser', 'filter' => ['status' => User::STATUS_ACTIVE], 'message' => 'There is no user with such email.']

    检查输入的两个值是否一致

    ['passwordRepeat', 'required'] // 必须要加上这一句 ['passwordRepeat', 'compare', 'compareAttribute' => 'password', 'operator' => '===']

    验证密码

    ['password', 'validatePassword', 'message' => '密码不正确']  //这里的validatePassword是自己在model下的类里定义的方法

    注意:这里的validatePassword是不能为Private的,必需是public

    数值范围检查

    1 ['age', 'compare', 'compareValue' => 30, 'operator' => '>=']
    2 ['level', 'in', 'range' => [1, 2, 3]]

    使用自定义函数过滤

    ['email', 'filter', 'filter' => function($value) {     // 在此处标准化输入的email     return strtolower($value); }]

    文件上传

    ['textFile', 'file', 'extensions' => ['txt', 'rtf', 'doc'], 'maxSize' => 1024 * 1024 * 1024]

    图片上传

    ['avatar', 'image', 'extensions' => ['png', 'jpg'],     'minWidth' => 100, 'maxWidth' => 1000,     'minHeight' => 100, 'maxHeight' => 1000, ]

    使用正则表达式

    ['username', 'match', 'pattern' => '/^[a-z]w*$/i']

    提示:打印出Validator::$builtInValidators可以看到被支持的所有validators

     1 Array
     2 (
     3     [boolean] => yiivalidatorsBooleanValidator
     4     [captcha] => yiicaptchaCaptchaValidator
     5     [compare] => yiivalidatorsCompareValidator
     6     [date] => yiivalidatorsDateValidator
     7     [default] => yiivalidatorsDefaultValueValidator
     8     [double] => yiivalidatorsNumberValidator
     9     [each] => yiivalidatorsEachValidator
    10     [email] => yiivalidatorsEmailValidator
    11     [exist] => yiivalidatorsExistValidator
    12     [file] => yiivalidatorsFileValidator
    13     [filter] => yiivalidatorsFilterValidator
    14     [image] => yiivalidatorsImageValidator
    15     [in] => yiivalidatorsRangeValidator
    16     [integer] => Array
    17         (
    18             [class] => yiivalidatorsNumberValidator
    19             [integerOnly] => 1
    20         )
    21     [match] => yiivalidatorsRegularExpressionValidator
    22     [number] => yiivalidatorsNumberValidator
    23     [required] => yiivalidatorsRequiredValidator
    24     [safe] => yiivalidatorsSafeValidator
    25     [string] => yiivalidatorsStringValidator
    26     [trim] => Array
    27         (
    28             [class] => yiivalidatorsFilterValidator
    29             [filter] => trim
    30             [skipOnArray] => 1
    31         )
    32     [unique] => yiivalidatorsUniqueValidator
    33     [url] => yiivalidatorsUrlValidator
    34     [ip] => yiivalidatorsIpValidator
    35 )

    注意:如果需要看里面的祥细代码,那么可以直接定位到里面的类里,里面的变量就是其属性

    使用示例如下:

     1 public function rules()
     2 {
     3     return array(
     4         //必须填写
     5         array('email, username, password,agree,verifyPassword,verifyCode', 'required'),
     6         //检查用户名是否重复
     7         array('email','unique','message'=>'用户名已占用'),
     8         //用户输入最大的字符限制
     9         array('email, username', 'length', 'max'=>64),
    10         //限制用户最小长度和最大长度
    11         array('username', 'length', 'max'=>7, 'min'=>2, 'tooLong'=>'用户名请输入长度为4-14个字符', 'tooShort'=>'用户名请输入长度为2-7个字'),
    12         //限制密码最小长度和最大长度
    13         array('password', 'length', 'max'=>22, 'min'=>6, 'tooLong'=>'密码请输入长度为6-22位字符', 'tooShort'=>'密码请输入长度为6-22位字符'),
    14         //判断用户输入的是否是邮件
    15         array('email','email','message'=>'邮箱格式错误'),
    16         //检查用户输入的密码是否是一样的
    17         array('verifyPassword', 'compare', 'compareAttribute'=>'password', 'message'=>'请再输入确认密码'),
    18         //检查用户是否同意协议条款
    19         array('agree', 'required', 'requiredValue'=>true,'message'=>'请确认是否同意隐私权协议条款'),
    20         //判断是否是日期格式
    21         array('created', 'date', 'format'=>'yyyy/MM/dd/ HH:mm:ss'),
    22         //判断是否包含输入的字符
    23         array('superuser', 'in', 'range' => array(0, 1)),
    24         //正则验证器:       
    25         array('name','match','pattern'=>'/^[a-z0-9-_]+$/'),
    26         //数字验证器:              
    27         array('id', 'numerical', 'min'=>1, 'max'=>10, 'integerOnly'=>true),
    28         //类型验证 integer,float,string,array,date,time,datetime                
    29         array('created', 'type', 'datetime'),
    30         //文件验证:       
    31         array('filename', 'file', 'allowEmpty'=>true, 'types'=>'zip, rar, xls, pdf, ppt','tooLarge'=>'图片不要超过800K'),
    32               array('url', 
    33                 'file',    //定义为file类型 
    34                 'allowEmpty'=>true,  
    35                 'types'=>'jpg,png,gif,doc,docx,pdf,xls,xlsx,zip,rar,ppt,pptx',   //上传文件的类型 
    36                 'maxSize'=>1024*1024*10,    //上传大小限制,注意不是php.ini中的上传文件大小 
    37                 'tooLarge'=>'文件大于10M,上传失败!请上传小于10M的文件!' 
    38             ), 
    39  } );

     rules里on的用法:

    //如果配置了on的场景,在调用的时候需要声明场景否则会全部验证
    [['title', 'content'], 'required', 'on' => ['add']],
    //也可以用except来替代on表示除了指定的场不需要验证,其他的都需要验证 //声明场景 $model->setScenario('add'); //or $model->scenario = 'update';

     7、在进行文件上传,制作uploadForm的时候,需要注意formname这个字段必需和传上来的name一致,如果没有的话,需要返回空字符串,否则系统无法读取数据

    use yiiaseModel;
    
    class UploadForm extends Model
    {
        public $file;
    
        public function formName()
        {
            return '';
        }
    
        public function rules()
        {
            return [
                ['file', 'file', 'mimeTypes' => ['image/*', 'video/*'], 'maxSize' => 100 * 1024 * 1024 * 1024]
            ];
        }
    
        public function upload () {
            if($this->validate()) {
    //            var_dump($this->file);
            } else {
                var_dump($this->getFirstErrors());
            }
        }
    
    }
  • 相关阅读:
    Dotnet微服务:使用HttpclientFactory实现服务之间的通信
    Dotnet微服务:使用Steeltoe集成Eureka
    Lora服务器:Chirpstack连接Lora网关实战
    linux远程windwos软件rdesktop
    kali笔记
    ubuntu笔记
    Swagger使用
    Swagger接口导入Yapi
    Nexus上传自己本地jar包 和下载maven中央仓库里的包到nexus
    docker安装rabbitmq
  • 原文地址:https://www.cnblogs.com/rickyctbu/p/12941895.html
Copyright © 2020-2023  润新知