构建和谐的PHP框架–构建模版引擎(3)美学原理

事先我们贯彻了最简便易行的echo指令的模版替换,就是将{{ $name }}如此这般一段内容替换成<?php echo $name ?>

今昔大家来说下任何的授命,先来回顾下在此以前的定义

  • 出口变量值

{{ }} 表明式的再次来到值将被活动传送给 PHPhtmlentities
函数举办拍卖,以预防 XSS 攻击。

Hello, {{ $name }}!
  • 输出未转义的变量值

    Hello, {!! $name !!}!

  • If 表达式

通过 @if@elseif@else@endif美学原理, 指令可以创制 if 表达式。

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
  • 循环

    @for ($i = 0; $i < 10; $i++)

    The current value is {{ $i }}
    

    @endfor

    @foreach ($users as $user)

    <p>This is user {{ $user->id }}</p>
    

    @endforeach

    @while (true)

    <p>I'm looping forever.</p>
    

    @endwhile

  • 引入其他视图

    @include(‘view.name’, [‘some’ => ‘data’])

要配合这多少个概念,我们要写出相应的正则表明式,关于@起始的授命直接拿了laravel中的使用。

咱俩先在src下创建view文件夹,再创建Compiler类文件。

我们将compiler的格局氛围二种,一种是@始发的指令(Statements),一种是出口(Echos)。这两种的正则是不平等的。

先是定义变量compliers,定义如下:

protected $compilers = [
    'Statements',
    'Echos',
];

接下来按着见原本Controllerrender主意的始末迁移到Complier类中,按这两种依次匹配,代码如下:

public function compile($path = null)
{
    $fileContent = file_get_contents($path);
    $result = '';
    foreach (token_get_all($fileContent) as $token) {
        if (is_array($token)) {
            list($id, $content) = $token;
            if ($id == T_INLINE_HTML) {
                foreach ($this->compilers as $type) {
                    $content = $this->{"compile{$type}"}($content);
                }
            }
            $result .= $content;
        } else {
            $result .= $token;
        }
    }
    $generatedFile = '../runtime/cache/' . md5($path);
    file_put_contents($generatedFile, $result);
    require_once $generatedFile;
}

protected function compileStatements($content)
{
    return $content;
}

protected function compileEchos($content)
{
    return preg_replace('/{{(.*)}}/', '<?php echo $1 ?>', $content);
}

其中的Statements完全没有拍卖,Echos则依然跟此前同一。

先来调整下Echos中的处理,添加变量记录{{ }}{!! !!}的名称

protected $echoCompilers = [
    'RawEchos',
    'EscapedEchos'
];

拍卖的时候可以增长一下留存的判定,默认值是null,内容能够调动如下:

protected function compileEchos($content)
{
    foreach ($this->echoCompilers as $type) {
        $content = $this->{"compile{$type}"}($content);
    }
    return $content;
}

protected function compileEscapedEchos($content)
{
    return preg_replace('/{{(.*)}}/', '<?php echo htmlentities(isset($1) ? $1 : null) ?>', $content);
}

protected function compileRawEchos($content)
{
    return preg_replace('/{!!(.*)!!}/', '<?php echo isset($1) ? $1 : null ?>', $content);
}

EscapedEchosRawEchos的区分在于,第一个会做html转义。

大家再来看Statements指令的拍卖,其规律也同样,匹配到对应的命令,如ifforeach,调用相应的措施做替换。

代码如下:

protected function compileStatements($content)
{
    return preg_replace_callback(
            '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?/x', function ($match) {
            return $this->compileStatement($match);
        }, $content
    );
}

protected function compileStatement($match)
{
    if (strpos($match[1], '@') !== false) {
        $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1];
    } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) {
        $match[0] = $this->$method(isset($match[3]) ? $match[3] : null);
    }

    return isset($match[3]) ? $match[0] : $match[0].$match[2];
}

protected function compileIf($expression)
{
    return "<?php if{$expression}: ?>";
}

protected function compileElseif($expression)
{
    return "<?php elseif{$expression}: ?>";
}

protected function compileElse($expression)
{
    return "<?php else{$expression}: ?>";
}

protected function compileEndif($expression)
{
    return '<?php endif; ?>';
}

protected function compileFor($expression)
{
    return "<?php for{$expression}: ?>";
}

protected function compileEndfor($expression)
{
    return '<?php endfor; ?>';
}

protected function compileForeach($expression)
{
    return "<?php foreach{$expression}: ?>";
}

protected function compileEndforeach($expression)
{
    return '<?php endforeach; ?>';
}

protected function compileWhile($expression)
{
    return "<?php while{$expression}: ?>";
}

protected function compileEndwhile($expression)
{
    return '<?php endwhile; ?>';
}

protected function compileContinue($expression)
{
    return '<?php continue; ?>';
}

protected function compileBreak($expression)
{
    return '<?php break; ?>';
}

其中的include实现相比较费心,就从不做,留给我们想想啦。

然后,大家再考虑一下,不容许每回都去操作文件再次生成,我应该要认清文件改变,假设没改变一向运用缓存就可以了。

调整代码如下:

public function isExpired($path)
{
    $compiled = $this->getCompiledPath($path);
    if (!file_exists($compiled)) {
        return true;
    }

    return filemtime($path) >= filemtime($compiled);
}

protected function getCompiledPath($path)
{
    return '../runtime/cache/' . md5($path);
}

public function compile($file = null, $params = [])
{
    $path = '../views/' . $file . '.sf';
    extract($params);
    if (!$this->isExpired($path)) {
        $compiled = $this->getCompiledPath($path);
        require_once $compiled;
        return;
    }
    $fileContent = file_get_contents($path);
    $result = '';
    foreach (token_get_all($fileContent) as $token) {
        if (is_array($token)) {
            list($id, $content) = $token;
            if ($id == T_INLINE_HTML) {
                foreach ($this->compilers as $type) {
                    $content = $this->{"compile{$type}"}($content);
                }
            }
            $result .= $content;
        } else {
            $result .= $token;
        }
    }
    $compiled = $this->getCompiledPath($path);
    file_put_contents($compiled, $result);
    require_once $compiled;
}

其一类另外博客到那边就临时告一段落了~

品种内容和博客内容也都会停放Github上,欢迎我们提提议。

code:https://github.com/CraryPrimitiveMan/simple-framework/tree/1.2

blog
project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework