在模仿Yii写框架的时候一直不知道Yii的render方法是怎么样去把渲染视图和布局文件放在一起的然后自己想方设法去用了一个创建临时文件的方法实现了
$content = file_get_contents('template.php');
$layouts = file_get_contents('layout.php');
$newphp = preg_replace('$content', $content, $layouts); // 在layout.php里面有一个$content的变量,用字符替换的方式把它换掉
file_put_contents($tmpName, $newphp); // 写入一临时文件
require_once $tmpName;
unlink($tmpName);但是始终觉得写入临时文件的方法很憋扭,然后又想出了另一种方法
$content = function(){
require './view.php';
};
//在布局文件中写
echo $content()
这样感觉还是不错的,可是必竟没有弄懂Yii的render不甘心,所幸硬着头皮去看看yii的源码吧,然然找到了yii的render是怎么实现的
/*** Renders a view file.
* This method includes the view file as a PHP script
* and captures the display result if required.
* @param string $viewFile view file
* @param array $data data to be extracted and made available to the view file
* @param boolean $return whether the rendering result should be returned as a string
* @return string the rendering result. Null if the rendering result is not required.
*/
public function renderInternal($viewFile,$data=null,$return=false)
{
// we use special variable names here to avoid conflict when extracting data
if(is_array($data))
extract($data,EXTR_PREFIX_SAME,'data');
else
$data=$data;
if($return)
{
ob_start();
ob_implicit_flush(false);
require($viewFile);
return ob_get_clean();
}
else
require($viewFile);
}
这才使的我大悟,之前搜索怎么得到执行后的php效果,有人把curl都用上了。结果原来用ob_start()相关的方法就可以了
所以最后我的render方法也跟着yii改进了
/*
渲染php文件,并返回渲染后的效果
@param str $file_path 文件路径
@param array $variable 渲染需要传进去的变量
@return string 渲染后的字符
/
private function renderFile($file_path, $variableArr) {
extract($variableArr);
ob_start();
ob_implicit_flush(false);
require($file_path);
return ob_get_clean();
}### 小插曲
在想到第二种方法的时候我搜索用php执行php代码,给我找到一个create_function函数
create_function(string $args, string $code)
string $args 变量部分,传到$code中的变量
string $code 方法代码部分,最终执行的代码,注间每行结束一定要打;号
//example
$code = 'require ./img.php'; //要执行的代码
$func = create_function('$content', $code);
$res = $func('param param'); //$func调用,传参相当于$content = 'param param';
var_dump($res); //没有返回值故为null
/**
img中的代码
<?php
echo 'img img img';
echo $content;
*/