Yii2.0学习笔记完全版word资料19页.doc

上传人:1595****071 文档编号:33864987 上传时间:2022-08-12 格式:DOC 页数:19 大小:231.50KB
返回 下载 相关 举报
Yii2.0学习笔记完全版word资料19页.doc_第1页
第1页 / 共19页
Yii2.0学习笔记完全版word资料19页.doc_第2页
第2页 / 共19页
点击查看更多>>
资源描述

《Yii2.0学习笔记完全版word资料19页.doc》由会员分享,可在线阅读,更多相关《Yii2.0学习笔记完全版word资料19页.doc(19页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、如有侵权,请联系网站删除,仅供学习与交流Yii2.0学习笔记完全版【精品文档】第 19 页Yii2.0学习笔记1. 搭建环境及目录结构1.1搭建环境参考1: Yii2.0框架下载安装 - Yii中文网 http:/www.yii-参考2:yii2.0-advanced 高级版项目搭建(一) http:/www.yii-1.2.目录结构basic/ 应用根目录composer.json Composer 配置文件, 描述包信息config/ 包含应用配置及其它配置console.php 控制台应用配置信息web.php Web 应用配置信息commands/ 包含控制台命令类controller

2、s/ 包含控制器类models/ 包含模型类runtime/ 包含 Yii 在运行时生成的文件,例如日志和缓存文件vendor/ 包含已经安装的 Composer 包,包括 Yii 框架自身views/ 包含视图文件web/ Web 应用根目录,包含 Web 入口文件assets/ 包含 Yii 发布的资源文件(javascript 和 css)index.php 应用入口文件yii Yii 控制台命令执行脚本2.一些常规配置2.1框架源的设置在配置文件web.php中如下配置$config = vendorPath = D:xampphtdocswwwyii2-vendor,2.2设置默认布

3、局2)在所在的控制器中加入,public $layout=mymain;2.3设置默认控制器在yii2-vendoryiisoftyii2web. Application.php中public $defaultRoute = index;/默认路由2.4设置默认首页在配置文件web.php中如下配置,$config = defaultRoute=index,/设置默认路由2.5数据库连接配置在配置文件db.php中如下配置,本人数据库为wxj,用户名root,密码为空 yiidbConnection, dsn = mysql:host=localhost;dbname=wxj, usernam

4、e = root, password = , charset = utf8,;2.6配置虚拟主机1)修改虚拟主机配置文件:xamppapacheconfextrahttpd-vhosts.conf。给定相应的域名和地址 DocumentRoot D:xampphtdocswwwSQprojectWeixinPayweb ServerName paycenter.social- ErrorLog logs/dummy-error.log CustomLog logs/dummy-access.log common2)找到C:WindowsSystem32driversetchosts添加127.

5、0.0.1paycenter.social-3)在URL地址中直接输入paycenter.social-3数据模型model3.1 model格式Model类也是更多高级模型如Active Record 活动记录的基类,模型并不强制一定要继承yiibaseModel,但是由于很多组件支持yiibaseModel,最好使用它做为模型基类。在model中主要是指定相应的表名和相应的规则3.2 model数据库连接在配置文件db.php中return class = yiidbConnection, dsn = mysql:host=localhost;dbname=wxj, username =

6、root, password = , charset = utf8,3.3 model中的增删改查在做增删改查是要引用数据模型 use WeixinPaymodelsWpUsers;3.3.1添加数据$model = newUser();$model-username = username;$model-age = 20;$model-insert();3.3.2删除数据User:deleteAll(name = 小伙儿); 删除 name = 小伙儿 的数据;User:findOne($id)-delete(); 删除主键为 $id变量 值的数据库;User:deleteAll(age :a

7、ge AND sex = :sex, :age = 20, :sex = 1); 删除符合条件的数据;3.3.3修改数据先查询到用户名与密码匹配的数据再修改其密码-执行写入动作$rel = WpUsers:findOne(username = $username, password = $oldpassword);$rel-password = $password;if ($rel-save()3.3.4查询单表查询User:find()-orderBy(id DESC)-all(); 此方法是排序查询;User:findBySql(SELECT * FROM user)-all(); 此方法

8、是用 sql 语句查询 user 表里面的所有数据;User:find()-andWhere(sex = 男, age = 24)-count(id); 统计符合条件的总条数;User:findOne($id); /返回 主键 id=1 的一条数据;User:find()-where(name = ttt)-one(); /返回 name = ttt 的一条数据;在用户表中以姓名为查询条件$info = WpUsers:find()-where(username = $username)-asArray()-all();在用户表中以姓名和密码为查询条件$re = WpUsers:find()-

9、where(username = $username, password = $password)-asArray()-all();多表查询用户表与角色表联合查询$id = $re0id;$list = WpUsers:find()-joinWith(wpRole)-where(wp_users.id = $id)-all();3.4数据验证在model中写一个rules方法进行验证,public function rules() return teacher_id, name, price, address, class_time, limit_num, description, requi

10、red, message = 请输入attribute, on = create, update , limit_num, teacher_id, number, message = 请填入正确的attribute, on = create, update, class_time, compare_time, message = attribute不能小于当前时间, on = create, update, limit_num, compare, compareValue = $this-use_num, operator = , message = attribute不能大于已招人数,已招人

11、数为: . $this-use_num, on = update , description, safe ;注意,有些验证类型不支持message,mobile, string, min = 11, max = 11, tooShort = attribute位数为11位, tooLong = attribute位数为11位, on = create, update,消息提示在tooShort和tooLong上面4视图层view4.1格式在views文件夹下建与控制器中的方法同名文件夹(所有文件夹名称小写)视图文件为php文件,视图文件与1.1版本类似4.2注册CSS或JS方法:方法一:1)因

12、在asset/AppAset.php中封装了一个类如下:namespace appassets;use yiiwebAssetBundle; * author Qiang Xue * since 2.0class AppAsset extends AssetBundle public $basePath = webroot; public $baseUrl = web; public $css = css/site.css, css/bootstrap.min.css,/布局 css/font-awesome.min.css,/小图标 css/ace-fonts.css,/字体 css/ace

13、.min.css,/公共部分 public $js = js/jquery-2.0.3.min.js, js/bootstrap.min.js, js/ace.min.js, js/ace-extra.min.js, public $depends = yiiwebYiiAsset, yiibootstrapBootstrapAsset,2)即在视图文件中只需引用该类use appassetsAppAsset;AppAsset:register($this);即可调用公共的类文件3)如需个性化调用方法二:1)类似方法一,在asset/AppAset.php中封装了一个类如下封装的注册js方法p

14、ublic static function initJsAssets($js = ,$position = 3) if(is_array($js) & !empty($js) foreach ($js as $key = $value) if(!is_array($valuejs) self:initJsAssets($valuejs,$valueposition); self:$obj-registerJsFile(self:$appAsset-baseUrl./js/.$js.?v=.Yii:getAlias(webStaticJsVersion), position=$position)

15、;2)在视图文件中先引用该类:如此便可以加载公共文件use WeixinPayassetsAppAsset;AppAsset:initAssets($this);3)如需个性化加载useWeixinPayassetsAppAsset;AppAsset:initCssAssets(ace-skins.min.css,$this:POS_HEAD);beginPage()?head()?beginBody();?endBody();?endPage()?5控制器层controller5.1控制器格式1)与1.1版本类似控制器名采用大驼峰式命名,注意使用命名空间;方法名采用小驼峰命名2)如需使用自定

16、义的布局 public $layout = common;如果某方法下不采用布局文件,可在方法内 : $this-layout = false;清除公共布局也可写一个方法控制:如下代码(指定login与rest页面布局不生效)/*清除公共布局*(non-PHPdoc)*seeyiiwebController:beforeAction()publicfunctionbeforeAction($action)if(!parent:beforeAction($action)returnfalse;if($action-id=loginor$action-id=reset)$this-layout=f

17、alse;returntrue;5.2 模板显示并传值return $this-render(login);return $this-render(sigleinfo, info = $info);return $this-redirect(Url:toRoute(wp-users/updatepwd);5.3 页面提示消息1)在控制器中成功:$session-set(username,yii:$app-request-post(username);失败:Yii:$app-getSession()-setFlash(error,您的用户名或密码输入错误);2)在views中先使用useyiib

18、ootstrapAlert;再写提示信息getSession()-hasFlash(success)echoAlert:widget(options=class=alert-success,/这里是提示框的classbody=Yii:$app-getSession()-getFlash(success),/消息体if(Yii:$app-getSession()-hasFlash(error)echoAlert:widget(options=class=alert-error,body=Yii:$app-getSession()-getFlash(error),5.4 post,get,sess

19、ion的使用yii:$app-request-post(password);yii:$app-session-get(username);/打开sessionuseyiiwebSession;$session=Yii:$app-session;$session-open();/设置session$session=Yii:$app-session;$session-set(user_id,1234);/销毁session$session=Yii:$app-session;$session-remove(user_id);$session = yii:$app-session;$session-o

20、pen();$session-set(username,yii:$app-request-post(username);(yii:$app-session-get(username)6.gii的使用6.1gii的配置1)在config/web.php配置文件中if (YII_ENV_DEV) $configbootstrap = gii; $configmodulesgii = class = yiigiiModule, / allowedIPs = 127.0.0.1, / 按需调整这里2)在入口文件index.php中defined(YII_ENV) or define(YII_ENV,

21、dev);3)通过 URL 访问 Gii:http:/localhost/index.php?r=gii6.2用 Gii 去生成数据表操作的增查改删(CRUD)代码CRUD 代表增,查,改,删操作,这是绝大多数 Web 站点常用的数据处理方式。选择 Gii 中的 “CRUD Generator” (点击 Gii 首页的链接)去创建 CRUD 功能。之前的 “product” 例子需要像这样填写表单:Model Class: appmodelsProduct Search Model Class:appmodels ProductSearchController Class:appcontrol

22、lers ProductController如果你之前创建过controllers/ProductController.php和views/product/index.php文件选中 “overwrite” 下的复选框覆写它们(之前的文件没能全部支持 CRUD)。http:/hostname/index.php?r=product/index可以看到一个栅格显示着从数据表中获取的数据。支持在列头对数据进行排序,输入筛选条件进行筛选。可以浏览详情,编辑,或删除栅格中的每个产品。还可以点击栅格上方的 “Create Product” 按钮通过表单创建新商品。总结:gii功能强大,使用 Gii 生成

23、代码把 Web 开发中多数繁杂的过程转化为仅仅填写几个表单就行。7.几个重要应用模块7.1分页7.1.1 Pagination1)引用分页类useyiidataPagination;2)获取总条数$total=Myuser:find()-count();3)实例化分页类并给参数$pages=newPagination(totalCount=$total,pageSize=2);4)获取数$rows=Myuser:find()-offset($pages-offset)-limit($pages-limit)-asArray()-all();5)显示模板并传值return$this-render

24、(oper,rows=$rows,pages=$pages,);6)模板显示$pages);?7.1.2ActiveDataProvider(gii方法)1)namespaceappcontrollers;2)useyiidataActiveDataProvider;3)$model=newMyuser();$dataProvider=newActiveDataProvider(query=$model-find(),pagination=pagesize=10,/若是用gii自动生成的则在此改/$this-load($params);return$dataProvider;return$th

25、is-render(oper,model=$model,dataProvider=$dataProvider,);7.1.3代码实例在控制器中查询总条数,实例化分页类,给定总条数及每页显示记录数,传值给模板use yiidataPagination;$total = WpOrder:find()-where($where)-count();$pages = new Pagination(totalCount = $total, pageSize = 10);$rows = WpOrder:find()-where($where)-offset($pages-offset)-limit($pag

26、es-limit)-asArray()-all();return $this-render(index, rows = $rows, pages = $pages, state = yii:$app-request-get(status), id = yii:$app-request-get(mch_id), Merchant=$Merchant);在视图显示中,设置显示效果(首页,末页) $pages, firstPageLabel = 首页, lastPageLabel = 末页, prevPageLabel = 上一页, nextPageLabel = 下一页,); ?7.2.文件上传7

27、.2.1单文件上传NewsController中public function actionCreate() $model = new News(); $rootPath = uploads/; $thumbPath = thumb/; if (isset($_POSTNews) $model-attributes = $_POSTNews; $image = UploadedFile:getInstance($model, image); $ext = $image-getExtension();/获取扩展名 $randName = time() . rand(1000, 9999) . .

28、 . $ext; $path = date(Y-m-d); $rootPath = $rootPath . $path . /; $thumbPath = $thumbPath . $path . /; /echo $rootPath;exit(); if (!file_exists($rootPath) mkdir($rootPath, true, 0777); if (!file_exists($thumbPath) mkdir($thumbPath, true); $re = $image-saveAs($rootPath . $randName);/返回bool值 $imageInfo

29、 = $model-image = $rootPath . $randName; $model-image = $imageInfo; if (!$model-save() print_r($model-getErrors(); if ($re) $this-redirect(Url:toRoute(create); else return $this-render(create, model = $model,); 验证规则如下(New.php)public function rules() return title, image, content, required, content, s

30、tring, title, string, max = 50, /image, string, max = 100, image,file,extensions=png,jpg,mimeTypes=image/png,image/jpeg, ;7.2.2多文件上传更改之处_Form.php中field($model, image)-fileInput(multiple=true) ?NewsController中public function actionCreate() $model = new News(); $rootPath = uploads/; $thumbPath = thumb

31、/; if (isset($_POSTNews) $model-attributes = $_POSTNews; $images = $model-file = UploadedFile:getInstances($model, image); / $ext = $this-file-extension; $path = date(Y-m-d); $rootPath = $rootPath . $path . /; $thumbPath = $thumbPath . $path . /; /echo $rootPath;exit(); if (!file_exists($rootPath) m

32、kdir($rootPath, false, 0777); if (!file_exists($thumbPath) mkdir($thumbPath, false); foreach ($images as $image) $ext = $image-getExtension();/获取扩展名 $randName = time() . rand(1000, 9999) . . . $ext; $re = $image-saveAs($rootPath . $randName);/返回bool值 $imageInfo = $model-image = $rootPath . $randName

33、; $model-image = $imageInfo; if (!$model-save() print_r($model-getErrors(); if ($re) $this-redirect(Url:toRoute(create); else return $this-render(create, model = $model,); 7.3验证码1)创建数据表,在表中写验证规则/* 验证码验证规则* return array*/public function rules() return verify,captcha ;2)控制器 class = yiiwebErrorAction,

34、, captcha = class = yiicaptchaCaptchaAction, fixedVerifyCode = YII_ENV_TEST ? testme : null, backColor = 0x000000,/背景颜色 maxLength = 6, /最大显示个数 minLength = 5,/最少显示个数 padding = 5,/间距 height = 40,/高度 width = 130, /宽度 foreColor = 0xffffff, /字体颜色 offset = 4, /设置字符偏移量 有效果 , ; public function behaviors() return access = class = AccessControl:className(), / class = yiicaptchaCaptchaAction, only = logout, signup, login,/这里一定要加 rules =

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 小学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com