您的位置:首页 > 编程语言 > PHP开发

Yii2学习笔记(二):慕课网视频教程笔记

2015-07-08 15:26 661 查看
1、下图是框架的目录结构



其中:controllers存放控制器文件、models存放数据库的模型文件、views存放视图文件,web下面的index.php是入口文件

在页面中运行http://localhost/basic/web/index.php?r=hello/hello:

(1)下面是controllers里面的HelloController.php文件:

<?php
//如何启动这个控制文件:运行web/index.php?r=hello/hello即可
//其中r代表参数,第一个hello是控制器的名字,第二个是动作的名字
namespace app\controllers;
use yii\web\Controller;
use yii\web\Cookie;
use app\models\test;//数据模型的命名空间

class HelloController extends Controller
{
public $layout='comm';
//服务器在响应时可以在头部加个lastModified和etag,当浏览器器再次发送请求时,
//会带上这两个参数,然后服务器进行比对,如果lastModified一致,那么etag肯定一致
//如果lastModified不一致,就会判断etag是否一致,再决定是否重新生成响应内容
//一般情况下,lastModified是时间戳,etag是业务处理方面的一些内容
public function behaviors()
{
return
[
[
'class'=>'yii\filters\HttpCache',
'lastModified'=>function()
{
return filemtime('hw.txt');

},
'etagSeed'=>function()
{
$fp = fopen('hw.txt','r');
$title = fgets($fp);
fclose($fp);
return $title;
}
]

];
}

public function actionHello()
{
//四、http缓存实例
$content=file_get_contents('hw.txt');

return $this->renderPartial('test2',['new'=>$content]);

//三、页面缓存

//二、片段缓存:详情在cache.php中
//	return $this->renderpartial('cache');

//一、数据缓存
//1、获取缓存组件
$cache=\YII::$app->cache;
/*		//往缓存中写数据
$cache->add('key1','hello');//如果添加的key值相等,那么缓存就会忽略
$cache->add('key1','hello3');//后面的添加,以第一个添加的为准,
//比如这个就会显示key1为hello
//读缓存
$data=$cache->get('key1');
//修改缓存
//$cache->set('key1','hello2');
//删除数据
//$cache->delete('key1');
//清空所有数据
//$cache->flush();
var_dump($data);//显示boolean false;

//2、缓存有效期设置
//测试的时候,先运行add,并注释掉echo,运行页面;
//然后注释掉add,运行echo,过5s后再次刷新,会发现没有显示
//$cache->add('key2','hello2',5);
//set也可以
//$cache->set('key2','hello2',5);
//echo $cache->get('key2');

//3、缓存中的依赖关系
//(1)文件依赖
//如果修改文件hw的内容,那么缓存就会立即失效,hw文件在web目录下
//$dependency=new \yii\caching\FileDependency(['fileName'=>'hw.txt']);
//$cache->add('key3','hello3',3000,$dependency);
//var_dump($cache->get('key3'));
//(2)表达式依赖
//下面的表达式是URL的请求参数,如果修改请求参数name的值,cache就失效
//$dependency=new \yii\caching\ExpressionDependency(['expression'=>'\YII::$app->request->get("name")']);
//$cache->add('key4','hello4',3000,$dependency);
//var_dump($cache->get('key4'));
//(3)DB依赖
//通过sql语句来依赖,如果sql语句返回的值有变化,那么cache就失效
//$dependency=new \yii\caching\DbDependency([
//	'sql'=>'select count(*) from db_bcty365.test']);
//$cache->add('db_key','hello db',3000,$dependency);
//var_dump($cache->get('db_key'));

//类的映射机制:减少系统查询类的时间
//	\YII::$classMap['app\models\test']='G:\PHP\basic\models\test.php';
//	$test=new Test;<span style="font-family: Arial, Helvetica, sans-serif;">会跳到autoLoad($class)函数,</span><span style="font-family: Arial, Helvetica, sans-serif;">并赋值'命名空间+test类名'给$class,如果没有上面的映射语句,系统会将$class转换成对应的绝               <span style="white-space:pre">			</span>//<span style="white-space:pre">		</span>对路径来查找test类,这个过程也是很消耗时间的;但是如果用了上面的映射语句,</span>此时系统就会直接使用映射的绝对路径,从而减少了系统开销

*/
//数据模型的操作
/*	//查询语句
//下面是四种方式,主要用第四种
//1、最常用的查询方式
$sql="select * from test where id=1";
$results=Test::findBySql($sql)->all();//返回一个数组

//2、根据用户提交的变量来查询
$id=1;
$sql="select * from test where id=".$id;
$results=Test::findBySql($sql)->all();//返回一个数组

//3、因为2存在SQL注入问题,所以出现了3这种方法
$sql="select * from Test where name=:name1";
//下面这个做法是为了防止SQL注入,比如一个用户输入了'a or name=b',那么执行查询语句就会查找a和b两个用户的内容
//这样显然是不安全的,因此YII提供了一种方法,就是在findBySql的第二个参数出添加一个数组,然后sql语句中
//使用如上所示的:name1的表示形式,这样就会把name1的内容当成一个整体来执行,而不会当成部分sql代码
$results=Test::findBySql($sql,array('name1'=>'a or name=b'))->all();//返回一个数组,这个语句返回一条name为'a or name =b'的内容

//4、因为3比较繁琐,因此出现了4
//name='a'的数据
//	$results=Test::find()->where(['name'=>'a'])->all();
//id>0的数据
//	$results=Test::find()->where(['>','id',0])->all();
//id>=1和id<=2的数据
//	$results=Test::find()->where(['between','id',1,2])->all();
//name like "%a%"
//	$results=Test::find()->where(['like','name','a'])->all();
//降低内存开销的方式:
//1、将结果从对象转化成数组
$results=Test::find()->where(['between','id',1,2])->asarray()->all();//此时显示结果为数组形式
print_r($results);
//2、批量查询
foreach(Test::find()->batch(10) as $array)//batch(10)就是每次从数据库中拿10条数据放到内存中,保存到变量array中
{
print_r($array);
}
*/
//删除语句
//1、单个删除
//	$results=Test::find()->where(['id'=>1])->all();
//	$results[0]->delete();
//2、多个删除
//	Test::deleteAll('id>:id',array(':id'=>2));

//添加数据
//插入数据时有个验证的过程,验证规则rules写在test.php类里面
/*	$test=new Test;
$test->id=5;
$test->name='hh';
$test->validate();
if($test->hasErrors())
{
echo 'data is error';
die;
}
$test->save();//保存到数据库中
*/

//修改数据
//$test=Test::find()->where(['id'=>5])->one();//通过one()返回一个对象
//$test->name="aa";
//$test->save();

//数据块的使用
//return $this->render('about');

//	return $this->renderPartial('about');

/*
//公共文件
render方法干两件事情:
一、把后面的参数存到$content变量中
二、会把布局文件显示出来,这个布局文件就是公共属性$layout的值
return $this->render('about');

//视图之间的数据传递:从控制器传到视图index.php
总共有三步
一、定义要传递的数据
//1、传递字符串变量
$str='hello<script>alert(3);<script>';
//2、传递数组
$str_array=array(1,2);
二、定义一个数组,用来存放要传递的数据
$data=array();
$data['view_str']=$str;
$data['view_str_array']=$str_array;
三、将数组放到renderPartial()的第二个参数
return $this->renderPartial('index',$data);

$request=\YII::$app->request;
echo $request->get('id',20);
if($request->isGet)
{
echo "this is a get";
}
echo $request->userIp;
echo "hello world!";

//	$response=\YII::$app->response;
//	$response->headers->add('param','no-cache');
//	$response->headers->set('param','max-age');
//	$response->headers->add('location','http://www.baidu.com');
//	$this->redirect('http://www.baidu.com');
//	$response->sendFile('./robots.txt');

//session

$session = \YII::$app->session;
$session->open();
if($session->isActive)
{
echo "session is active";
}

//	$session->set('user','3');
//	echo $session->get('user');
//	$session['user']=4;
//	echo $session->get('user');
//	unset($session['user']);
//	echo $session->get('user');

//cookie
//	$cookie=\YII::$app->response->cookies;
//	$cookie_data=array('name'=>'1','value'=>'2');
//	$cookie->add(new Cookie($cookie_data));
//	echo $cookie->get('1');

//	$cookie->remove('id');

//	$cookie=\YII::$app->request->cookies;
//	echo $cookie->getValue('1',20);  这个有问题,显示不出来cookie为1的值
*/
}
}


(2)models/test.php,数据模型文件

<?php
namespace app\models;
use yii\db\ActiveRecord;
//1、文件名必须和类名一致
//2、文件名必须为表名
//也就是说:文件名、表名和类名都要一致
class Test extends ActiveRecord
{

}

?>


(3)views/layout/comm.php公共文件,即一些常用的顶部和底部代码

<html>
<head>
</head>
<body>
<?=$content?>
<!--进行判断:如果存在block,就显示block;
不存在,就显示comm原先的内容
注意:if和else后面都有冒号:
最后还有个endif-->
<?php if(isset($this->blocks['block1'])):?>
<?=$this->blocks['block1']?>
<?php else:?>
<h1>hello comm</h1>
<?php endif;?>
</body>
</html>


(4)views/hello/about.php:视图之数据块的使用,和comm.php结合使用,在comm.php中调用这个block来覆盖原有的内容

<h1>hello about!</h1>
<!--视图之数据块-->
<?php $this->beginBlock('block1');?>
<h1>this is block</h1>
<?php $this->endBlock();?>

<!--1、在一个视图中显示另一个视图
2、同时,还可以给test.php传参,通过给render方法添加第二个参数,这个参数只能是关联数组
然后再test.php调用$v_test就可以显示了
3、注意:可以render多次,即添加多个页面
4、不能使用renderPartial()方法
-->
<?php echo $this->render('test',array('a'=>'hello world'));?>
<?php echo $this->render('test2');?>


(5)views/hello/index.php,这个hello文件夹是hello动作执行时要查找的对应的文件夹,用来显示页面

<?php
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
?>
<!--显示从控制器传过来的数据,$view_str存在数组中的值-->
<h1><?=$view_str?></h1>
<!--encode对变量中存在的js脚本进行转义,使其不运行,只是单纯的显示-->
<h1><?=Html::encode($view_str);?></h1>
<!--process方法彻底清除变量中存在的js脚本,连显示都没有了-->
<h1><?=HtmlPurifier::process($view_str_array[0]);?></h1>


(6)views/hello/cache.php,片段缓存文件

<?php
//缓存时间
//过了15,缓存就会失效,从而显示修改后的值
$duration=15;
//缓存依赖,跟数据缓存依赖一样
$dependency=[
'class'=>'yii\caching\FileDependency',
'fileName'=>'hw.txt'
];
//缓存的开关
$enable=false;
?>
<!--缓存开关的使用-->
<?php
if($this->beginCache('cache_div',['enabled'=>$enable])){
?>
<!--通过缓存时间来设置cache失效的时间-->
<?php
// if($this->beginCache('cache_div',['duration'=>$duration])){
?>

<!--通过缓存依赖来控制cache失效的时间-->
<?php
// if($this->beginCache('cache_div',['dependency'=>$dependency])){
?>

<!--下面的内容会被添加到缓存,如果修改了里面的内容,那么显示的内容
还是原来的内容-->
<div id='cache_div'>
这里会被缓存11
</div>
<?php
$this->endCache();
}
?>

<div id='no_cache_div'>
这里不会被缓存
</div>


(7)views/hello/test.php,测试文件

<h2>hello test</h2>
<h1><?=$a?></h1>
(8)views/hello/test2.php,测试文件

<h1><?=$new?></h1>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: