Yii2.0学习笔记完全版word资料19页.doc
如有侵权,请联系网站删除,仅供学习与交流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/ 包含控制台命令类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 <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.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' =>