Yii2.0学习笔记完全版.doc_第1页
Yii2.0学习笔记完全版.doc_第2页
Yii2.0学习笔记完全版.doc_第3页
Yii2.0学习笔记完全版.doc_第4页
Yii2.0学习笔记完全版.doc_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Yii2.0学习笔记1. 搭建环境及目录结构1.1搭建环境参考1: Yii2.0框架下载安装 - Yii中文网 /post/detail/35.html参考2:yii2.0-advanced 高级版项目搭建(一) /post/detail/1.html1.2.目录结构basic/ 应用根目录composer.json Composer 配置文件, 描述包信息config/ 包含应用配置及其它配置console.php 控制台应用配置信息web.php Web 应用配置信息commands/ 包含控制台命令类controllers/ 包含控制器类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设置默认布局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, username = root, password = , charset = utf8,;2.6配置虚拟主机1)修改虚拟主机配置文件:xamppapacheconfextrahttpd-vhosts.conf。给定相应的域名和地址 DocumentRoot D:xampphtdocswwwSQprojectWeixinPayweb ServerName ErrorLog logs/-error.log CustomLog logs/-access.log common2)找到C:WindowsSystem32driversetchosts添加3)在URL地址中直接输入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 = 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 :age 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(); 此方法是用 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()-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, required, 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不能大于已招人数,已招人数为: . $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)因在asset/AppAset.php中封装了一个类如下:namespace appassets;use yiiwebAssetBundle;/* * author Qiang Xue * since 2.0 */class 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.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方法public 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);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)如需使用自定义的布局 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=false;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中先使用useyiibootstrapAlert;再写提示信息getSession()-hasFlash(success)echoAlert:widget(options=class=alert-success,/这里是提示框的class,body=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,session的使用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-open();$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 = , / 按需调整这里 ;2)在入口文件index.php中defined(YII_ENV) or define(YII_ENV, 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:appcontrollers ProductController如果你之前创建过controllers/ProductController.php和views/product/index.php文件选中 “overwrite” 下的复选框覆写它们(之前的文件没能全部支持 CRUD)。http:/hostname/index.php?r=product/index可以看到一个栅格显示着从数据表中获取的数据。支持在列头对数据进行排序,输入筛选条件进行筛选。可以浏览详情,编辑,或删除栅格中的每个产品。还可以点击栅格上方的 “Create Product” 按钮通过表单创建新商品。总结:gii功能强大,使用 Gii 生成代码把 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(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$this-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($pages-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.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) . . . $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 = $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, string, 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/; 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) mkdir($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; $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, , 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 = actions = login, captcha, allow = true, roles = ?, , actions = logout, edit, add, del, index, users, thumb, upload, cutpic, follow, nofollow , allow = true, roles = , , , , verbs = class = VerbFilter:className(), actions = logout = post, , , ; public function actionIndex() $model = new Myuser(); if (Yii:$app-request-isPost) $userName = Yii:$app-request-post(userName); $passWord = Yii:$app-request-post(password); $re = Myuser:find()-where(userName = $userName, password = $passWord)-one(); /$re = Myuser:find()-where(userName = $userName, password = $passWord)-asArray()-one(); / var_dump($re);exit(); if ($re != null) echo 登录成功; $this-redirect(Url:toRoute(index/index); /echo Url:toRoute(index / index); else echo 登录失败; return $this-render(index, model = $model); 3)显示模板由于是在原来的基础上改的,因此部分input是自己写的 user-form ) ? user: pwd : field($model, verify)-textInput(maxlength = 30) ? captchaimg, imageOptions = id = captchaimg, captchaAction = login/captcha, title = 换一个, alt = 换一个, style = cursor:pointer;margin-left:25px; , template = image);? a href=管理7.4 Url美化a期望路径格式:http:/localhost/user/index.htmlb在config/web.php中改配置,具体如下/开启重写功能urlManager = enablePrettyUrl = true, showScriptName = false, suffix=.html,/即以.html结尾 rules= ,c.在/basic/web下面添加.htaccess文件至此成功

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论