YII安装和使用
一、下载安装
解决证书错误
http://www.yiichina.com/doc/guide/2.0/start-installation
其中前面步骤都是安装composer的东西。若安装了composer可以直接到第六步
下载安装包安装
安装basic时,访问index出错,需要在config中的web.php配置 'cookieValidationKey' => 'huwei',
二、使用
1、基础篇
命名空间
不带命名空间的类为全局类,使用时带“\”
声明命名空间
namespace tests\b;class apple{function get_info(){echo "this is b";}}
使用命名空间
require_once("a.php");require_once("b.php");require_once("c.php");use tests\a\apple;use tests\b\apple as bApple;$a=new apple();$a->get_info();echo "<br/>";$b=new bApple();$b->get_info();echo "<br/>";$c=new \Apple();//全局类$c->get_info();
请求组件
//请求组件$request=YII::$app->request;echo $request->get('id',20);//get 两个参数,若第二个参数不传,echo $request->post('id',20);//get 两个参数,若第二个参数不传,if($request->isGet){echo "this is get method";}
响应组件
//响应组件$response=Yii::$app->response;$response->statusCode='404';$response->headers->add('pragma','no-cache');$response->headers->add('pragma','max-age-5');$response->headers->remove('pragma');//自动跳转//$response->headers->add('location','http://www.baidu.com');//$this->redirect('http://www.baidu.com',302);//文件下载//$response->headers->add('content-disposition','attachment;filename="a.jpg"');$response->sendFile('./robots.txt');
session组件
//session组件//一个浏览器不能使用另外一个浏览器保存的session$session=YII::$app->session;//开启session//将session保存在php.ini中设置好的路径 session.save_path = "C:/wamp/www/tmp"$session->open();if($session->isActive){//添加session// $session->set('user','huwei');//使用sessionecho $session->get('user');//删除session$session->remove('user');//使用数组进行session使用$session['user']='huwei';unset($session['user']);//去除数组}
视图
<?php/*** Created by PhpStorm.* User: huwei* Date: 2015/10/14* Time: 21:08*/namespace app\controllers;use yii\web\controller;use yii;use yii\web\Cookie;classIndexControllerextendsController{//使用布局文件public $layout='common';publicfunction actionGrid(){$hello='hello_grid<script>alert(111);</script>';$arr=array(1,2);$data=array();$data['view_str_hello']=$hello;$data['view_arr_arr']=$arr;return $this->render('grid',$data);}}
<?phpuse yii\helpers\Html;use yii\helpers\HtmlPurifier;?>tihs is grid<!--数据安全--><h1><?=Html::encode($view_str_hello)?></h1><!--解码script--><h1><?=HtmlPurifier::process($view_str_hello)?></h1><!--过滤script--><?php//数据传递$str="<table>";foreach($view_arr_arr as $k){$str.="<tr><td>".$k."</td>";$str.="</tr>";}$str.="</table>";print $str;?><?php//在视图文件中打开另一个视图文件并传值$data=array();$data['view_str_hello']=$view_str_hello;echo $this->render('add',$data);?><!--使用数据块--><?php $this->beginBlock('block1');?><h1>this is grid block</h1><?php $this->endBlock();?>
<!DOCTYPE html><html><headlang="en"><metacharset="UTF-8"><title></title></head><body><h1>this is common</h1><!--使用数据块--><?php if(isset($this->blocks['block1'])):?><?=$this->blocks['block1'];?><?php else:?><h1>this is common11</h1><?php endif;?><?=$content?></body></html>
数据模型
publicfunction actionIndex(){//查询数据//通过原生sql语句//http://www.yiichina.com/doc/api/2.0/yii-db-query#where%28%29-detail$sql='select * from user where is_delete=:is_delete';//:is_delete是个占位符 防止sql注入$data=User::findBySql($sql,array(':is_delete'=>0))->all();//通过内置方法$data=User::find()->where(['is_delete'=>0])->all();//查询结果转换为数组$data=User::find()->where(['is_delete'=>0])->asArray()->all();//批量查询 一次查询10条数据foreach(User::find()->batch(10)as $userData){//print_r($userData);}//删除数据$data=User::find()->where(['is_delete'=>1])->all();//删除单条//$data[0]->delete();//删除满足条件的所有数据User::deleteAll('is_delete=:is_delete',array(':is_delete'=>1));//添加数据$user=newUser();$user['name']='sd';$user['account_id']=1;$user->save();//修改数据$data=User::find()->where(['id'=>1])->one();$data['name']='胡伟';$data->save();//关联查询//根据用户查找帐号信息//最好封装在model中$user=User::find()->where(['is_delete'=>0])->all();$account= $user[0]->hasMany('app\models\Account',['id'=>'account_id'])->asArray()->all();$account= $user[0]->hasMany(Account::className(),['id'=>'account_id'])->asArray()->all();//只要在User的model中封装了getAccounts便可这样使用//等同于调用getAccounts()方法$account=$user[0]->account;//关联查询的结果会被缓存//关联查询的多次查询//select * from user//select * from account where id in (...)$user=User::find()->with('account')->all();//等同于$user=User::find()->all();foreach($user as $u){$account=$u->account;}print_r($user);return $this->render('index');}
classUserextendsActiveRecord{//合法性验证//http://www.yiichina.com/doc/guide/2.0/tutorial-core-validatorspublicfunction rules(){return[['account_id','integer'],['name','string','length'=>[0,5]]];}publicfunction getAccount(){//hasOne$account= $this->hasMany(Account::className(),['id'=>'account_id'])->asArray();return $account;}}
2、工具篇
composer
在window下安装了composer后,配置好了环境变量就可以直接使用composer了。
在每个程序包中都配置好了composer.json ,在该文件中配置好需要的程序包,第一次,使用install便可下载所有的特定的依赖包,之后便可以使用update命令来更新程序包了。
create-project 创建程序项目
使用composer镜像
1.
在命令行中使用
composer config -g repositories.packagist composer http://packagist.phpcomposer.com
2.在composer.json下面添加
"repositories":[{"type":"composer","url":"http://packagist.phpcomposer.com"},{"packagist":false}]
debug工具
可以用composer require yiisoft/yii2-debug 2.0.5进行下载
不过在YII2自带的composer.json中也有dubug工具的更新
性能监视
在Database中可以查看数据库操作的执行时间等情况,
在profiling中可以记录程序某个片段的执行时间等情况。
片段使用方法
yii::beginProfile('profile1');echo 'hello profile';sleep(1);yii::endProfile('profile1');

gii工具
YII场景
publicfunction actionGii(){$test=newGiiTest;//指定需要加载的场景,使用load方法将该值赋给该对象的属性//只有在场景中申明的才能赋予//实际用于增加和修改的不同操作$test->scenario='scenario2';$testData=['data'=>['id'=>3,'title'=>'hello word']];$test->load($testData,'data');$test->title='title4';$test->save();echo $test->title;print_r($test->id);}
publicstaticfunction tableName(){return'gii_test';}//创建场景publicfunction scenarios(){return['scenario1'=>['id','title'],'scenario2'=>['id']];}
CRUD Generator(CRUD生成器)

便可以生成GiiTest的CRUD操作,不过访问方式是gii-test
在进行增加和修改操作时需要给其添加场景
Form Generator

生成之后在控制器中使用该部件,不过需要传递一个model给它
publicfunction actionPublic(){$model=newGiiTest();return $this->renderPartial('/article/public',['model'=>$model]);}
Widget工具(部件)
部件创建
classTopMenuextendsWidget{publicfunction init(){parent::init();echo '<ul>';}publicfunction run(){return'</ul>';}publicfunction addMenu($menuName){return'<li>'.$menuName.'</li>';}}
使用
use app\components\TopMenu;?><div><?php $menu=TopMenu::begin();?><?=$menu->addMenu('menu1');?><?= $menu->addMenu('menu2');?><?php TopMenu::end();?></div>
浙公网安备 33010602011771号