rkr / view
更安全且易于使用的php5.4+模板系统
0.3
2023-01-05 12:17 UTC
Requires
- php: >= 7.4
Requires (Dev)
- phpstan/phpstan: >= 1.9
- phpunit/phpunit: ~3.7@stable
README
更安全且易于使用的php5.4+模板系统。
设计目标
- 接口驱动,依赖注入友好
- 默认安全,需要时才不安全
- 轻量级,易于理解和稳定
- 无需额外脚本语言。使用PHP编写模板。
启动
您需要某处将其转换为字符串的模板文件
$factory = new FileViewFactory(__DIR__.'/path/to/my/template/folder'); $renderer = $factory->create('module'); $renderer->add('myVar', 1234); $content = $renderer->render('action'); echo $content;
FileViewFactory
实现了一个名为 ViewFactory
的接口。您可以使用这个接口来构建自己的工厂,创建不同的渲染器等。这特别有用,如果您需要一种方法在未来更改实现。如果您使用依赖注入容器连接组件,这也很有用。
class MyCtrl { /** @var ViewFactory */ private $viewFactory; /** * @param ViewFactory $viewFactory */ public function __construct(ViewFactory $viewFactory) { $this->viewFactory = $viewFactory; } /** * @return string */ public function someAction() { $content = $this->viewFactory->create('module') ->add('myVar', 1234) ->render('action'); return $content; } }
使用类型提示
在PHP-Templates中,您可以使用IDE(如PHPStorm、ZendStudio或PDT等)所识别的类型提示。
index.phtml
<?php /* @var \View\Workers\Worker $this */ ?> <?php /* @var \Some\Name\Spaced\Object $obj */ ?> <?php $obj = $this->get('obj') ?> <div><?= $obj->getName() ?></div>
即使对于对象和方法调用,也启用转义
与其使用 $renderer->get('obj'),不如使用 $renderer->getObject('obj')。
index.phtml
<?php /* @var \View\Workers\Worker $this */ ?> <?php /* @var \Some\Name\Spaced\Object $obj */ ?> <?php $obj = $this->getObject('obj') ?> <div><?= $obj->getName() ?></div>
布局支持
index.phtml
<?php /* @var \View\Workers\Worker $this */ ?> <?php $this->layout('layout', ['title' => 'My Site']) ?> This will be part of the region "content". <?php $this->region('left') ?> This will be part of the region "left". <?php $this->end() ?>
layout.phtml
<?php /* @var \View\Workers\Worker $this */ ?> <html> <head> <title>MySite<?php if($this->has('title')): ?> - <?= $this->getString('title') ?><?php endif ?></title> </head> <body> <div id="content"> <?= $this->get('content') ?> </div> <div id="left"> <?= $this->get('left') ?> </div> </body> </html>