博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
构建自己的PHP框架--构建模版引擎(2)
阅读量:6863 次
发布时间:2019-06-26

本文共 2841 字,大约阅读时间需要 9 分钟。

自从来到新公司就一直很忙,最近这段时间终于稍微闲了一点,赶紧接着写这个系列,感觉再不写就烂尾了。

之前我们说到,拿到{

{ $name }}这样一段内容时,我们只需要将它转化成<?php echo $name ?>这样,就可以识别了,输出相应的变量值。

那就要需要正则匹配{

{ $name }},然后替换掉{
{
}},分别替换成<?php echo?>

但是要想到一个问题,如果我在 view 里写了 php 的代码,其中含有{

{ $name }},也会被替换。例子如下:

要解决这个问题,我们需要将 PHP 的代码去掉,只留下 html 代码再做替换的处理。幸好 PHP 有一个方法 token_get_all,会将提供的内容按 PHP 标记进行分割。使用此方法解析如下内容:

$content = <<
{
{ \$name }}VIEW;print_r(token_get_all($content));

这里$符号前加\是为了转移,在真正是现实不需要。结果如下:

Array(    [0] => Array        (            [0] => 379            [1] => 
1 ) [1] => Array ( [0] => 382 [1] => [2] => 2 ) [2] => = [3] => Array ( [0] => 382 [1] => [2] => 2 ) [4] => Array ( [0] => 323 [1] => 'test' [2] => 2 ) [5] => ; [6] => Array ( [0] => 382 [1] => [2] => 2 ) [7] => = [8] => Array ( [0] => 382 [1] => [2] => 3 ) [9] => " [10] => Array ( [0] => 322 [1] => {
{ [2] => 3 ) [11] => Array ( [0] => 320 [1] => $name [2] => 3 ) [12] => Array ( [0] => 322 [1] => }} [2] => 3 ) [13] => " [14] => ; [15] => Array ( [0] => 382 [1] => [2] => 3 ) [16] => Array ( [0] => 381 [1] => ?> [2] => 4 ) [17] => Array ( [0] => 321 [1] => {
{ $name }} [2] => 5 ))

可以看到 PHP 相关的代码被解析了,我们只需要判断出是 html 代码,然后做替换就可以了。其中的321就是定义好的常量T_INLINE_HTML的值,标记解析出来的就是 html 代码。

我们定义view文件的后缀为sf,那我们就可以在controller/model/view目录下创建view.sf文件,内容如下

{<div></div> { $title }}

{
{ $str }}

{

{ $body }}

然后我们来改造Controller中的render方法,代码如下

public function render($view, $params = []){    $file = '../views/' . $view . '.sf';    $fileContent = file_get_contents($file);    $result = '';    foreach (token_get_all($fileContent) as $token) {        if (is_array($token)) {            list($id, $content) = $token;            if ($id == T_INLINE_HTML) {                $content = preg_replace('/{
{(.*)}}/', '
', $content); } $result .= $content; } else { $result .= $token; } } $generatedFile = '../runtime/cache/' . md5($file); file_put_contents($generatedFile, $result); extract($params); require_once $generatedFile;}

修改actionView如下

public function actionView(){    $this->render('site/view', ['body' => 'Test body information']);}

访问 ,得到如下页面

587057-20170608202049184-782679762.png

今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。

code:

blog project:

转载地址:http://ivqyl.baihongyu.com/

你可能感兴趣的文章
地对地导弹地对地导弹地对地导弹
查看>>
让div 充满整个body
查看>>
程序员保持快乐活跃的6个好习惯(转)
查看>>
找工作的一些感悟——前端小菜的成长
查看>>
jSON Call can throw but it is not marked with try
查看>>
Javascript图片裁切
查看>>
Android -- Serializable和Parcelable需要注意的
查看>>
Apache -- phpmyadmin导入文件过大
查看>>
我的友情链接
查看>>
一分钟看懂Docker的网络模式和跨主机通信
查看>>
数据中悲观锁和乐观锁的理解
查看>>
能想到登录失败是这原因么
查看>>
Shiro 权限管理filterChainDefinitions过滤器配置
查看>>
我的友情链接
查看>>
Python 文件I/Oday14
查看>>
回忆Spring IOC 几个注解&简单示例
查看>>
及时更新网卡驱动可使无线网络更稳定
查看>>
在if中赋值,但在if外却提示“使用了未赋值的局部变量”
查看>>
MapReduce源码之OutputFormat
查看>>
资质申报 - 系统集成企业资质等级评定条件实施细则
查看>>