mcuelenaere / plitz
Blitz 的纯 PHP 版本
0.0.4
2016-03-06 12:29 UTC
Requires
- php: >=5.5
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0
- satooshi/php-coveralls: ~0.6
- symfony/yaml: ~2.6
This package is auto-updated.
Last update: 2024-08-29 04:35:36 UTC
README
Plitz 是 Blitz PHP 模板扩展的纯 PHP 版本,其源代码位于 https://github.com/alexeyrybak/blitz。
安装
使用 composer 安装
composer require mcuelenaere/plitz
用法
使用 Plitz 提供的功能有两种方式
Blitz 兼容层
$template = <<<EOF Hello {{ audience }}! EOF ; $assignments = [ 'audience' => 'world' ]; // construct Blitz object $blitz = new Plitz\Bindings\Blitz\Blitz(); // load template $blitz->load($template); // render template to stdout $blitz->display($assignments);
直接访问 Plitz 类
$template = <<<EOF Hello {{ audience }}! EOF ; $assignments = [ 'audience' => 'world' ]; // wrap template in a simple data:// stream $inputStream = fopen("data://text/plain;base64," . base64_encode($template), "r"); // write compiled template to a memory buffer $outputStream = fopen("php://memory", "r+"); try { // setup the required infrastructure $lexer = new Plitz\Lexer\Lexer($inputStream, "no template filename available"); $compiler = new Plitz\Compilers\PhpCompiler($outputStream); // or perhaps you want the Plitz\Compilers\JsCompiler ? $parser = new Plitz\Parser\Parser($lexer->lex(), $compiler); // lex and parse from the input stream and compile to the output stream $parser->parse(); // retrieve the compiled code from the memory stream fseek($outputStream, 0, SEEK_SET); $compiledCode = stream_get_contents($outputStream); } catch (Plitz\Lexer\LexException $ex) { printf("We got an exception from the lexer: %s (%s: line %d, pos %d)", $ex->getMessage(), $ex->getTemplateName(), $ex->getTemplateLine(), $ex->getTemplateColumn()); exit(1); } catch (Plitz\Parser\ParseException $ex) { printf("We got an exception from the parser: %s (%s: line %d, pos %d)", $ex->getMessage(), $ex->getTemplateName(), $ex->getTemplateLine(), $ex->getTemplateColumn()); exit(1); } finally { // cleanup when we're done fclose($inputStream); fclose($outputStream); } // create a function from the compiled code $templateFunction = create_function('$context', 'ob_start(); ?>' . $compiledCode . '<?php return ob_get_clean();'); // and last but not least: actually run it! echo $templateFunction($assignments);
设计
Plitz 由 4 个组件组成
- 词法分析器:将输入流标记化为
Plitz\Lexer\Tokens
流 - 解析器:解析
Plitz\Lexer\TokenStream
并通知Plitz\Parser\Visitor
解析的块 - 编译器:实现
Plitz\Parser\Visitor
类并将代码写入输出流 - Blitz 兼容层:将上述所有部分封装在一个类中,同时尽量保持与
Blitz
的源代码兼容性