Build a PHP framework and build a template engine instance
自从来到新公司就一直很忙,最近这段时间终于稍微闲了一点,赶紧接着写这个系列,感觉再不写就烂尾了。
之前我们说到,拿到{{ $name }}
这样一段内容时,我们只需要将它转化成<?php echo $name ?>
这样,就可以识别了,输出相应的变量值。
那就要需要正则匹配{{ $name }}
,然后替换掉{{
和}}
,分别替换成<?php echo
和?>
。
但是要想到一个问题,如果我在 view 里写了 php 的代码,其中含有{{ $name }}
,也会被替换。例子如下:
<?php$name = 'test';$str = "{{ $name }}";?>
要解决这个问题,我们需要将 PHP 的代码去掉,只留下 html 代码再做替换的处理。幸好 PHP 有一个方法 token_get_all,会将提供的内容按 PHP 标记进行分割。使用此方法解析如下内容:
$content = <<<VIEW<?php\$name = 'test';\$str = "{{ \$name }}";?><html> <body>{{ \$name }}</body><html>VIEW;print_r(token_get_all($content));
这里$
符号前加\
是为了转移,在真正是现实不需要。结果如下:
Array ( [0] => Array ( [0] => 379 [1] => <?php [2] => 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] => <html> <body>{{ $name }}</body> <html> [2] => 5 ) )
可以看到 PHP 相关的代码被解析了,我们只需要判断出是 html 代码,然后做替换就可以了。其中的321就是定义好的常量T_INLINE_HTML
的值,标记解析出来的就是 html 代码。
我们定义view文件的后缀为sf,那我们就可以在controller/model/view
目录下创建view.sf
文件,内容如下
<?php$title = 'It is a title';$str = "{{ $title }}";?><html> <head> <title>{{ $title }}</title> <head> <body> <h2>{{ $str }}</h2> <p>{{ $body }}<p> </body> </html>
然后我们来改造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('/{{(.*)}}/', '<?php echo $1 ?>', $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']);}
访问 http://localhost/simple-framework/public/index.php?r=site/view ,得到如下页面
今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。
code:
blog project:
The above is the detailed content of Build a PHP framework and build a template engine instance. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
