Yii2.0学习重点笔记完全版.doc
Yii2.0学习笔记1. 搭建环境及目录构造1.1搭建环境参照1: Yii2.0框架下载安装 - Yii中文网 参照2:yii2.0-advanced 高档版项目搭建(一) 1.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,密码为空<?phpreturn 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=localhost;dbname=wxj', 'username' => 'root', 'password' => '', 'charset' => 'utf8',;2.6配备虚拟主机1)修改虚拟主机配备文献:xamppapacheconfextrahttpd-vhosts.conf。给定相应域名和地址<VirtualHost *:80> DocumentRoot "D:xampphtdocswwwSQprojectWeixinPayweb" ServerName paycenter.social- ErrorLog "logs/dummy-error.log" CustomLog "logs/dummy-access.log" common</VirtualHost>2)找到C:WindowsSystem32driversetchosts添加127.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' => '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 = $re0'id'$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)如需个性化调用<?php echo Html:cssFile('web/assets/css/font-awesome.min.css')?>办法二: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($value'js') self:initJsAssets($value'js',$value'position'); self:$obj->registerJsFile(self:$appAsset->baseUrl.'/js/'.$js.'?v='.Yii:getAlias('webStaticJsVersion'),'position'=>$position);2)在视图文献中先引用该类:如此便可以加载公共文献use WeixinPayassetsAppAsset;AppAsset:initAssets($this);3)如需个性化加载use WeixinPayassetsAppAsset;AppAsset:initCssAssets('ace-skins.min.css',$this:POS_HEAD);<?php $this->beginPage() ?><?php $this->head() ?><?php $this->beginBody(); ?><?php $this->endBody(); ?> <?php $this->endPage() ?>5控制器层controller5.1控制器格式1)与1.1版本类似控制器名采用大驼峰式命名,注意使用命名空间;办法名采用小驼峰命名2)如需使用自定义布局 public $layout = 'common'如果某办法下不采用布局文献,可在办法内 : $this->layout = false;清除公共布局也可写一种办法控制:如下代码(指定login与rest页面布局不生效)/*清除公共布局 * (non-PHPdoc) * see yiiwebController:beforeAction() */public function beforeAction($action) if (!parent:beforeAction($action) return false; if ($action->id = 'login' or $action->id = 'reset') $this->layout = false; return true;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中先使用use yiibootstrapAlert;再写提示信息<?phpif (Yii:$app->getSession()->hasFlash('success') echo Alert:widget( 'options' => 'class' => 'alert-success', /这里是提示框class , 'body' => Yii:$app->getSession()->getFlash('success'), /消息体 );if (Yii:$app->getSession()->hasFlash('error') echo Alert: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');/打开session use yiiwebSession;$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) $config'bootstrap' = 'gii' $config'modules''gii' = 'class' => 'yiigiiModule', / 'allowedIPs' => '127.0.0.1',/ 按需调节这里 ;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) 引用分页类use yiidataPagination;2) 获取总条数$total = Myuser:find()->count();3) 实例化分页类并给参数$pages = new Pagination('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)模板显示<?= yiiwidgetsLinkPager:widget('pagination' => $pages); ?>7.1.2ActiveDataProvider(gii办法)1) namespace appcontrollers; 2)use yiidataActiveDataProvider; 3)$model = new Myuser(); $dataProvider = new ActiveDataProvider( '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);在视图显示中,设立显示效果(首页,末页)<?php echo yiiwidgetsLinkPager:widget( 'pagination' => $pages, 'firstPageLabel' => '首页', 'lastPageLabel' => '末页', 'prevPageLabel' => '上一页', 'nextPageLabel' => '下一页',);?>7.2.文献上传7.2.1单文献上传NewsController中public function actionCreate() $model = new News(); $rootPath = "uploads/" $thumbPath = "thumb/" if (isset($_POST'News') $model->attributes = $_POST'News' $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中<?= $form->field($model,'image')->fileInput('multiple'=>true) ?>NewsController中public function actionCreate() $model = new News(); $rootPath = "uploads/" $thumbPath = "thumb/" if (isset($_POST'News') $model->attributes = $_POST'News' $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)控制器<?phpnamespace appcontrollers;use appmodelsMyuser;use Yii;use yiihelpersUrl;use yiiwebController;use yiidataPagination;use yiifiltersAccessControl;use yiifiltersVerbFilter;class UserController extends Controller public $verify; public $layout = "mymain" public $enableCsrfValidation = false;/清除Unable to verify your data submission. / public $layout = false;/清除布局 public function action() return 'error' => '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',