前言
本文主要给大家介绍的是关于Yii2中负载()和保存()的相关内容,分享出来供大家参考学习,话不多说,来一起看看详细的介绍吧。
我这里用的数据库是蒙戈数据库为栗子:
公共函数加载($data,$ formName=null){ $ scope=$ formName===null?$ this-formName(): $ formName;//调用负荷一般我是$test=new test() $test-load('参数1','参数2')//参数一一般是post get传过来的参数第二个参数是一个空字符串'';//$this-formName()返回的额是你实例化的类的名字新测试()最后返回的是测试if ($scope===' '!empty($ data)){ $ this-setAttributes($ data);//进入返回真;} else if(isset($ data[$ scope]){ $ this-setAttributes($ data[$ scope]);返回真;} else {返回false} }接下来看setAttributes()
公共函数setAttributes($values,$ safe only=true){ if(is _ array($ values)){ $ attributes=array _ flip($ safe only?$ this-safe Attributes()$ : $ this-Attributes());//这里执行的是$this-safeAttributes()方法,该方法返回的是当前场景下需要验证的字段。最后$属性打印下来看下图foreach($ values as $ name=$ value){ if(isset($ attributes[$ name]){ $ this-$ name=$ value;} else if($ safe only){ $ this-ononsafaiattribute($ name,$ value);} } } }图: 图一的文件名是试验实例化后是$测试对象公共函数属性()方法中对应的就是表字段。
我这里没有用场景所以暂时不讲解场景这个功能。不过大家可以看手册。很容易懂。
这两个图是对相应的
在之后执行的是脚痛循环这里的$这个是那个$测试这个对象对象去调用
//例如邮政提交过来的数据是这样$post=['a'=123456,' b '=' abcdef ']$ test-a=123456 $ test-b=' abcdef '所以这个负载()方法只是分配邮政或者得到发过来的数据,不做验证。
接下来看save();
查看救援方法。
公共函数save($runValidation=true,$ attributename=null){ if($ this-getisnercord()){//判断是否是新纪录返回$this-insert($runValidation,$ attributename//执行这里之后$这个代表的是试验这个模型表//测试继承的是yiimongodbActiveRecord查看插入()方法. else { return $ this-update($ runValidation,$ attributeNames)!==false} }插入()方法中
公共函数insert($runValidation=true,$ attributes=null){ if($ runValidation!$ this-validate($ attributes)){//下面的代码分析生效方法验证规则返回false } $ result=$ this-插入内部($ attributes);//保存数据返回$ result}首先看
//进行数据验证公共函数validate($ attributename=null,$ ClearErrors=true){ if($ ClearErrors){ $ this-ClearErrors();} if(!$this-beforeValidate()) {//在验证之前首先执行的是beforValidata返回false } $ scenes=$ this-scenes();$ scenario=$ this-getScenario();//检查是否调用场景if(!isset($ scenarios[$ scenario]){抛出新的invalidpramexception('未知方案: $方案');} if($ AttributeNames===null){ $ AttributeNames=$ this-activeAttributes();//返回数组(值为属性的名称)}//$this-getActiveValidators()验证数据。读取规则方法getActiveValidators()-getValidators()-createValidators()这里验证规则等信息-createValidator()foreach($ this-getActiveValidators()as $ validator){ $ validator-validate属性($ this,$ attributename//获取交集检查是否有错误hasError()} $ this-after validate();回来!$ this-hasErrors();}此时数据验证完毕,之后就保存数据保存数据这块就暂时不写了后续补上。
好了其中数据验证那一块大家多看看源码吧。一遍不行2遍3遍多了就懂了。
总结
以上就是本文的全部内容。希望本文的内容能给你的学习或工作带来一些帮助。有问题可以留言交流。谢谢你的支持。