首页 > 技术文章 > YII安装和使用

kinmos 原文

一、下载安装

http://www.phperz.com/article/14/1211/40633.html
解决证书错误
http://my.oschina.net/yearnfar/blog/346727
 
http://www.yiichina.com/tutorial/324 
http://www.yiichina.com/doc/guide/2.0/start-installation
其中前面步骤都是安装composer的东西。若安装了composer可以直接到第六步
下载安装包安装
http://pandaju.me/article/177
 
安装basic时,访问index出错,需要在config中的web.php配置 'cookieValidationKey' => 'huwei',
 
二、使用
1、基础篇
命名空间
不带命名空间的类为全局类,使用时带“”
声明命名空间
  1. namespace tests;
  2. class apple{
  3. function get_info(){
  4. echo "this is b";
  5. }
  6. }
使用命名空间
  1. require_once("a.php");
  2. require_once("b.php");
  3. require_once("c.php");
  4. use testsaapple;
  5. use testsapple as bApple;
  6. $a=new apple();
  7. $a->get_info();
  8. echo "<br/>";
  9. $b=new bApple();
  10. $b->get_info();
  11. echo "<br/>";
  12. $c=new Apple();//全局类
  13. $c->get_info();
 
请求组件
  1. //请求组件
  2. $request=YII::$app->request;
  3. echo $request->get('id',20);//get 两个参数,若第二个参数不传,
  4. echo $request->post('id',20);//get 两个参数,若第二个参数不传,
  5. if($request->isGet){
  6. echo "this is get method";
  7. }
响应组件
  1. //响应组件
  2. $response=Yii::$app->response;
  3. $response->statusCode='404';
  4. $response->headers->add('pragma','no-cache');
  5. $response->headers->add('pragma','max-age-5');
  6. $response->headers->remove('pragma');
  7. //自动跳转
  8. //$response->headers->add('location','http://www.baidu.com');
  9. //$this->redirect('http://www.baidu.com',302);
  10. //文件下载
  11. //$response->headers->add('content-disposition','attachment;filename="a.jpg"');
  12. $response->sendFile('./robots.txt');
session组件
  1. //session组件
  2. //一个浏览器不能使用另外一个浏览器保存的session
  3. $session=YII::$app->session;
  4. //开启session
  5. //将session保存在php.ini中设置好的路径 session.save_path = "C:/wamp/www/tmp"
  6. $session->open();
  7. if($session->isActive){
  8. //添加session
  9. // $session->set('user','huwei');
  10. //使用session
  11. echo $session->get('user');
  12. //删除session
  13. $session->remove('user');
  14. //使用数组进行session使用
  15. $session['user']='huwei';
  16. unset($session['user']);//去除数组
  17. }
视图
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: huwei
  5. * Date: 2015/10/14
  6. * Time: 21:08
  7. */
  8. namespace appcontrollers;
  9. use yiiwebcontroller;
  10. use yii;
  11. use yiiwebCookie;
  12. classIndexControllerextendsController{
  13. //使用布局文件
  14. public $layout='common';
  15. publicfunction actionGrid(){
  16. $hello='hello_grid<script>alert(111);</script>';
  17. $arr=array(1,2);
  18. $data=array();
  19. $data['view_str_hello']=$hello;
  20. $data['view_arr_arr']=$arr;
  21. return $this->render('grid',$data);
  22. }
  23. }
  1. <?php
  2. use yiihelpersHtml;
  3. use yiihelpersHtmlPurifier;
  4. ?>
  5. tihs is grid
  6. <!--数据安全-->
  7. <h1><?=Html::encode($view_str_hello)?></h1><!--解码script-->
  8. <h1><?=HtmlPurifier::process($view_str_hello)?></h1><!--过滤script-->
  9. <?php
  10. //数据传递
  11. $str="<table>";
  12. foreach($view_arr_arr as $k){
  13. $str.="<tr><td>".$k."</td>";
  14. $str.="</tr>";
  15. }
  16. $str.="</table>";
  17. print $str;
  18. ?>
  19. <?php
  20. //在视图文件中打开另一个视图文件并传值
  21. $data=array();
  22. $data['view_str_hello']=$view_str_hello;
  23. echo $this->render('add',$data);
  24. ?>
  25. <!--使用数据块-->
  26. <?php $this->beginBlock('block1');?>
  27. <h1>this is grid block</h1>
  28. <?php $this->endBlock();?>
  1. <!DOCTYPE html>
  2. <html>
  3. <headlang="en">
  4. <metacharset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>this is common</h1>
  9. <!--使用数据块-->
  10. <?php if(isset($this->blocks['block1'])):?>
  11. <?=$this->blocks['block1'];?>
  12. <?php else:?>
  13. <h1>this is common11</h1>
  14. <?php endif;?>
  15. <?=$content?>
  16. </body>
  17. </html>
数据模型
  1. publicfunction actionIndex(){
  2. //查询数据
  3. //通过原生sql语句
  4. //http://www.yiichina.com/doc/api/2.0/yii-db-query#where%28%29-detail
  5. $sql='select * from user where is_delete=:is_delete';//:is_delete是个占位符 防止sql注入
  6. $data=User::findBySql($sql,array(':is_delete'=>0))->all();
  7. //通过内置方法
  8. $data=User::find()->where(['is_delete'=>0])->all();
  9. //查询结果转换为数组
  10. $data=User::find()->where(['is_delete'=>0])->asArray()->all();
  11. //批量查询 一次查询10条数据
  12. foreach(User::find()->batch(10)as $userData){
  13. //print_r($userData);
  14. }
  15. //删除数据
  16. $data=User::find()->where(['is_delete'=>1])->all();
  17. //删除单条
  18. //$data[0]->delete();
  19. //删除满足条件的所有数据
  20. User::deleteAll('is_delete=:is_delete',array(':is_delete'=>1));
  21. //添加数据
  22. $user=newUser();
  23. $user['name']='sd';
  24. $user['account_id']=1;
  25. $user->save();
  26. //修改数据
  27. $data=User::find()->where(['id'=>1])->one();
  28. $data['name']='胡伟';
  29. $data->save();
  30. //关联查询
  31. //根据用户查找帐号信息
  32. //最好封装在model中
  33. $user=User::find()->where(['is_delete'=>0])->all();
  34. $account= $user[0]->hasMany('appmodelsAccount',['id'=>'account_id'])->asArray()->all();
  35. $account= $user[0]->hasMany(Account::className(),['id'=>'account_id'])->asArray()->all();
  36. //只要在User的model中封装了getAccounts便可这样使用
  37. //等同于调用getAccounts()方法
  38. $account=$user[0]->account;
  39. //关联查询的结果会被缓存
  40. //关联查询的多次查询
  41. //select * from user
  42. //select * from account where id in (...)
  43. $user=User::find()->with('account')->all();
  44. //等同于
  45. $user=User::find()->all();
  46. foreach($user as $u){
  47. $account=$u->account;
  48. }
  49. print_r($user);
  50. return $this->render('index');
  51. }
  1. classUserextendsActiveRecord{
  2. //合法性验证
  3. //http://www.yiichina.com/doc/guide/2.0/tutorial-core-validators
  4. publicfunction rules(){
  5. return[
  6. ['account_id','integer'],
  7. ['name','string','length'=>[0,5]]
  8. ];
  9. }
  10. publicfunction getAccount(){
  11. //hasOne
  12. $account= $this->hasMany(Account::className(),['id'=>'account_id'])->asArray();
  13. return $account;
  14. }
  15. }
 
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下面添加
  1. "repositories":[
  2. {"type":"composer","url":"http://packagist.phpcomposer.com"},
  3. {"packagist":false}
  4. ]
debug工具
可以用composer require yiisoft/yii2-debug 2.0.5进行下载
不过在YII2自带的composer.json中也有dubug工具的更新
http://localhost:81/basic/web/index.php?r=debug中可以查看访问请求的所有信息
性能监视
在Database中可以查看数据库操作的执行时间等情况,
在profiling中可以记录程序某个片段的执行时间等情况。
片段使用方法
  1. yii::beginProfile('profile1');
  2. echo 'hello profile';
  3. sleep(1);
  4. yii::endProfile('profile1');
 
gii工具
http://localhost:81/basic/web/index.php?r=gii
YII场景
  1. publicfunction actionGii(){
  2. $test=newGiiTest;
  3. //指定需要加载的场景,使用load方法将该值赋给该对象的属性
  4. //只有在场景中申明的才能赋予
  5. //实际用于增加和修改的不同操作
  6. $test->scenario='scenario2';
  7. $testData=[
  8. 'data'=>['id'=>3,'title'=>'hello word']
  9. ];
  10. $test->load($testData,'data');
  11. $test->title='title4';
  12. $test->save();
  13. echo $test->title;
  14. print_r($test->id);
  15. }
  1. publicstaticfunction tableName(){
  2. return'gii_test';
  3. }
  4. //创建场景
  5. publicfunction scenarios(){
  6. return[
  7. 'scenario1'=>['id','title'],
  8. 'scenario2'=>['id']
  9. ];
  10. }
 
CRUD Generator(CRUD生成器)
便可以生成GiiTest的CRUD操作,不过访问方式是gii-test
在进行增加和修改操作时需要给其添加场景
 
Form Generator
生成之后在控制器中使用该部件,不过需要传递一个model给它
  1. publicfunction actionPublic(){
  2. $model=newGiiTest();
  3. return $this->renderPartial('/article/public',['model'=>$model]);
  4. }
 
 
Widget工具(部件)
部件创建
  1. classTopMenuextendsWidget{
  2. publicfunction init(){
  3. parent::init();
  4. echo '<ul>';
  5. }
  6. publicfunction run(){
  7. return'</ul>';
  8. }
  9. publicfunction addMenu($menuName){
  10. return'<li>'.$menuName.'</li>';
  11. }
  12. }
使用
  1. use appcomponentsTopMenu;
  2. ?>
  3. <div>
  4. <?php $menu=TopMenu::begin();?>
  5. <?=$menu->addMenu('menu1');?>
  6. <?= $menu->addMenu('menu2');?>
  7. <?php TopMenu::end();?>
  8. </div>
 
 
 



推荐阅读