Yii2.0学习重点笔记完全版.doc
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Yii2 学习 重点 笔记 完全
- 资源描述:
-
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:\xampp\htdocs\www\yii2-vendor',] 2.2设立默认布局 2)在所在控制器中加入, public $layout="mymain"; 2.3设立默认控制器 在yii2-vendor\yiisoft\yii2\web. Application.php中 public $defaultRoute = 'index';//默认路由 2.4设立默认首页 在配备文献web.php中如下配备, $config = [ 'defaultRoute'=>'index',//设立默认路由] 2.5数据库连接配备 在配备文献db.php中如下配备,本人数据库为wxj,顾客名root,密码为空 <?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=wxj', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]; 2.6配备虚拟主机 1)修改虚拟主机配备文献:xampp\apache\conf\extra\httpd-vhosts.conf。给定相应域名和地址 <VirtualHost *:80> DocumentRoot "D:\xampp\htdocs\www\SQproject\WeixinPay\web" ServerName paycenter.social- ErrorLog "logs/dummy--error.log" CustomLog "logs/dummy--access.log" common </VirtualHost> 2)找到C:\Windows\System32\drivers\etc\hosts 添加127.0.0.1 paycenter.social- 3)在URL地址中直接输入paycenter.social- 3.数据模型model 3.1 model格式 Model 类也是更多高档模型如Active Record 活动记录基类,模型并不强制一定要继承yii\base\Model,但是由于诸多组件支持yii\base\Model,最佳使用它做为模型基类。 在model中重要是指定相应表名和相应规则 3.2 model数据库连接 在配备文献db.php中 return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=wxj', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]; 3.3 model中增删改查 在做增删改查是要引用数据模型 use WeixinPay\models\WpUsers; 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 = $re[0]['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.视图层view 4.1格式 在views文献夹下建与控制器中办法同名文献夹(所有文献夹名称小写) 视图文献为php文献,视图文献与1.1版本类似 4.2注册CSS或JS办法: 办法一: 1)因在asset/AppAset.php中封装了一种类如下: namespace app\assets; use yii\web\AssetBundle; /** * @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 = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; } 2)即在视图文献中只需引用该类 use app\assets\AppAsset; 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 WeixinPay\assets\AppAsset; AppAsset::initAssets($this); 3)如需个性化加载 use WeixinPay\assets\AppAsset; 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.控制器层controller 5.1控制器格式 1)与1.1版本类似控制器名采用大驼峰式命名,注意使用命名空间;办法名采用小驼峰命名 2)如需使用自定义布局 public $layout = 'common';如果某办法下不采用布局文献,可在办法内 : $this->layout = false; 清除公共布局也可写一种办法控制:如下代码(指定login与rest页面布局不生效) /**清除公共布局 * (non-PHPdoc) * @see \yii\web\Controller::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 yii\bootstrap\Alert; 再写提示信息 <?php if (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 yii\web\Session; $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' => 'yii\gii\Module', // 'allowedIPs' => ['127.0.0.1'],// 按需调节这里 ]; } 2)在入口文献index.php中 defined('YII_ENV') or define('YII_ENV','dev'); 3)通过 URL 访问 Gii: http://localhost/index.php?r=gii 6.2用 Gii 去生成数据表操作增查改删(CRUD)代码 CRUD 代表增,查,改,删操作,这是绝大多数 Web 站点惯用数据解决方式。选取 Gii 中 “CRUD Generator” (点击 Gii 首页链接)去创立 CRUD 功能。之前 “product” 例子需要像这样填写表单: Model Class:app\models\Product Search Model Class: app\models\ ProductSearch Controller Class: app\controllers\ 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 Pagination 1) 引用分页类use yii\data\Pagination; 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)模板显示<?= \yii\widgets\LinkPager::widget(['pagination' => $pages]); ?> 7.1.2ActiveDataProvider(gii办法) 1) namespace app\controllers; 2)use yii\data\ActiveDataProvider; 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 yii\data\Pagination; 。。。。 $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 yii\widgets\LinkPager::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)控制器 <? php namespace app\controllers; use app\models\Myuser; use Yii; use yii\helpers\Url; use yii\web\Controller; use yii\data\Pagination; use yii\filters\AccessControl; use yii\filters\VerbFilter; 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' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', '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' => 'yii\captcha\CaptchaAction', 'only' => ['logout','signup','login'],//这里一定要加 'rules' => [ [ 'actions' => ['login','captcha'],展开阅读全文
咨信网温馨提示:1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,个别因单元格分列造成显示页码不一将协商解决,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前可先查看【教您几个在下载文档中可以更好的避免被坑】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时联系平台进行协调解决,联系【微信客服】、【QQ客服】,若有其他问题请点击或扫码反馈【服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【版权申诉】”,意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:0574-28810668;投诉电话:18658249818。




Yii2.0学习重点笔记完全版.doc



实名认证













自信AI助手
















微信客服
客服QQ
发送邮件
意见反馈



链接地址:https://www.zixin.com.cn/doc/3000117.html