peak/view

此包已被弃用且不再维护。未建议替代包。

PHP 最小化视图模板引擎,具有宏和助手。

1.1.0 2020-04-30 17:14 UTC

This package is auto-updated.

Last update: 2020-06-28 14:31:40 UTC


README

version License

快速且最小化的视图模板引擎,具有宏、助手和指令。

! 已弃用

此包已被标记为已弃用!如果需要,它可能还会接收错误修复,但这就是全部。我强烈建议用户切换到现代的 JS 前端框架,而不是使用 PHP 作为模板引擎。

安装

这是一个独立的包,并不随 peak/framework 自动提供。

$ composer require peak/view

基本用法

视图至少需要两样东西

  • 展示
  • 数据(或者变量,如果你喜欢的话)
$presentation = new SingleLayoutPresentation(
    '/path/to/layout1.php', 
    '/path/to/view1.php'
);
$data = [
    'title' => 'FooTheBar',
    'name' => 'JohnDoe'
];
$view = new View($data, $presentation);

视图模板示例

布局示例

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= $this->title ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <main>
        <?= $this->layoutContent ?>
    </main>
</body>
</html>

脚本示例(在布局中用 $this->layoutContent 表示)

<div class="container">
    hello <?= $this->name ?>
</div>

渲染视图

$output = $view->render();

创建复杂展示

$presentation = new Presentation([
    '/layout1.php' => [
        '/view1.php',
        '/layout2,php' => [
            '/view2.php',
            '/view3.php',
        ]
    ]
]);

宏是闭包,将绑定到你的视图类实例上。它们可以访问所有类属性和方法,因此必须谨慎使用。宏适用于小任务。

$view->addMacro('formatedName', function() {
    return ucfirst($this->name);
});

并在你的模板视图中

...
<h1>Hello <?= $this->formatedName() ?></h1>

助手

助手是一个独立的对象实例,它是 callable。与宏相反,助手不能直接访问视图属性和方法,但通常比宏更易于维护和更安全。助手适用于高级任务,并可以从依赖注入中受益。

助手类示例

class EscapeTextHelper
{
    public function __invoke($text)
    {
        return filter_var($text, FILTER_SANITIZE_SPECIAL_CHARS);
    }
}

在你可以使用它之前,你需要给你的视图助手一个函数名

$view->setHelpers([
    'escape' => new EscapeTextHelper(),
    // ...
]);

最后,你将能够像使用宏一样使用你的助手

...
<h1>Hello <?= $this->escape($this->name) ?></h1>

指令

指令为你提供了编写模板的更简单、更优雅的语法。默认情况下,在视图中没有启用任何指令。你需要使用 setDirectives() 方法将它们添加到视图实例中。指令的缺点是视图必须在渲染模板之后运行它们,这增加了一个额外的编译步骤。你拥有的指令越多,渲染视图所需的时间就越长。当然,这种副作用可以通过适当的缓存解决方案来减轻,但为了保持简单,Peak View 默认不提供。

$view->setDirectives([
    // give you ability to print variable with syntax {{ $myVar }}
    new EchoDirective(), 
    // give you ability to call native php functions, 
    // macros or helpers with syntax @function(...args)
    new FnDirective(),  
]);

$view->addVars([
    'name' => 'bob'
    'messages' => [
        // ...
    ],
    'items' => [
        'property' => 'value'
    ]
]);

template.php

<h1>Hello {{ $name }}</h1>

<p>You can call native php function with @</p>
<h4>@date(l \t\h\e jS) - You have @count($messages) message(s)</h4>

<p>You can also call helpers and macros too</p>
<p>@escape($name)</p>

<p>You can still use directly PHP like this: <?= $this->name; ?></p>

<p>And finally, array variable can be accessed with DotNotation syntax: {{ $items.property }}</p>

重要的是要记住,在你的模板中,PHP 首先执行,然后编译/渲染指令。

你还可以使用 DirectiveInterface 创建你自己的指令。