视图集成
Kuiper Web 模块支持多种模板引擎,包括 PHP 原生模板和 Twig 模板引擎。视图系统将数据与模板分离,使页面维护更加简单。
视图概述
视图接口
所有视图实现都遵循 ViewInterface 接口:
<?php
declare(strict_types=1);
namespace kuiper\web\view;
interface ViewInterface
{
/**
* 渲染视图
*
* @param string $name 视图名称
* @param array $context 模板变量
* @return string 渲染后的内容
*/
public function render(string $name, array $context = []): string;
}视图的注入
容器配置里加上 WebConfiguration 后,实现了 ViewAwareInterface 的组件(控制器等)会自动注入视图, 视图按 application.web.view 配置创建,控制器里不需要自己 new PhpView()。
控制器需要同时满足三个条件:继承 AbstractController、使用 ControllerTrait (它内部使用了 ViewAwareTrait,提供 render() / renderAsString() 和 $view 属性)、 实现 kuiper\web\view\ViewAwareInterface——容器靠这个接口做自动注入:
<?php
declare(strict_types=1);
namespace App\controller;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use kuiper\web\view\ViewAwareInterface;
use Psr\Http\Message\ResponseInterface;
#[Controller]
class HomeController extends AbstractController implements ViewAwareInterface
{
use ControllerTrait;
#[GetMapping('/')]
public function index(): ResponseInterface
{
return $this->render('home', [
'title' => 'Welcome',
'users' => ['Alice', 'Bob', 'Charlie'],
]);
}
}render() 返回写入了渲染结果的响应对象,可以继续调用 withHeader() / withStatus(); renderAsString() 只返回渲染后的字符串,不写入响应。 也可以在构造函数里直接注入 ViewInterface,见在控制器中注入视图。
视图引擎的选择
WebConfiguration 按下面的规则创建 ViewInterface:
| 条件 | 视图 |
|---|---|
application.web.view.engine 为 php | PhpView |
为 twig 且安装了 twig/twig | TwigView |
| 未配置 | 安装了 twig/twig 就用 TwigView,否则用 PhpView |
注意最后一行:twig 可能只是其它包间接带进来的依赖,模板是 PHP 文件的项目应显式配置 'engine' => 'php'。
模板目录由 application.web.view.path 指定,默认 {application.base_path}/resources/views (环境变量 WEB_VIEW_PATH、WEB_VIEW_ENGINE)。
模板扩展名(application.web.view.extension)的默认值:PhpView 默认 .php; TwigView 默认没有扩展名——模板名要自带后缀,或显式配置 extension。
PhpView
基本使用
PhpView 用 PHP 文件做模板,文件名是「模板名 + .php」。
创建视图模板 resources/views/home.php:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title><?= $__helpers::e($title) ?></title>
</head>
<body>
<h1><?= $__helpers::e($title) ?></h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?= $__helpers::e($user) ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>模板变量
模板中可以直接访问传递的变量,如 $title 和 $users。转义输出用 $__helpers::e() ($__helpers 是渲染时自动注入的 kuiper\web\view\ViewHelpers 实例)。
自动转义
PhpView 的第三个构造参数为 true 时开启自动转义,上下文里的标量值(以及数组里的标量值) 在渲染前都会被 htmlspecialchars() 处理:
<?php
declare(strict_types=1);
use kuiper\web\view\PhpView;
$view = new PhpView(
__DIR__ . '/../../views',
'.php',
true, // 启用自动转义
true // 注入 $__helpers 视图辅助
);<?= $userInput ?> <!-- 自动转义 -->通过容器创建的 PhpView 默认不开启自动转义,模板里需要显式调用 $__helpers::e()。
视图辅助函数
渲染时 PhpView 会向模板注入一个 ViewHelpers 实例 $__helpers,可用的方法都是静态方法:
| 方法 | 用途 |
|---|---|
$__helpers::e($value) | HTML 转义 |
$__helpers::raw($value) | 原样输出 |
$__helpers::js($value) | 转义为 JavaScript 字符串 |
$__helpers::url($value) | URL 编码 |
$__helpers::csrfField($token) | 生成 _token 隐藏字段 |
$__helpers::methodField($method) | 生成 _method 隐藏字段 |
<h1><?= $__helpers::e($user['name']) ?></h1>
<a href="/users?name=<?= $__helpers::url($name) ?>">查看</a>完整的 PHP 模板示例
<?php /* resources/views/users/list.php */ ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title><?= $__helpers::e($title) ?> - 用户列表</title>
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body>
<div class="container">
<h1><?= $__helpers::e($title) ?></h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $__helpers::e($user['id']) ?></td>
<td><?= $__helpers::e($user['name']) ?></td>
<td><?= $__helpers::e($user['email']) ?></td>
<td>
<a href="/users/<?= $__helpers::url($user['id']) ?>">查看</a>
<a href="/users/<?= $__helpers::url($user['id']) ?>/edit">编辑</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if ($totalPages > 1): ?>
<nav aria-label="分页导航">
<ul class="pagination">
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
<li class="<?= $i === $currentPage ? 'active' : '' ?>">
<a href="/users?page=<?= $i ?>"><?= $i ?></a>
</li>
<?php endfor; ?>
</ul>
</nav>
<?php endif; ?>
</div>
</body>
</html>TwigView
配置 Twig
首先安装 Twig:
composer require twig/twig基本使用
和 PhpView 一样,控制器实现 ViewAwareInterface 后由容器注入视图, 不要在控制器里自己 new TwigView():
<?php
declare(strict_types=1);
namespace App\controller;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use kuiper\web\view\ViewAwareInterface;
use Psr\Http\Message\ResponseInterface;
#[Controller]
class TwigController extends AbstractController implements ViewAwareInterface
{
use ControllerTrait;
#[GetMapping('/twig')]
public function index(): ResponseInterface
{
return $this->render('home.html', [
'title' => 'Welcome',
'users' => ['Alice', 'Bob', 'Charlie'],
]);
}
}TwigView 的扩展名默认为 null(见视图引擎的选择), 所以模板名写成 home.html,带上后缀。
Twig 模板
创建 Twig 模板 resources/views/home.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
</body>
</html>Twig 扩展
框架没有内置 url_for、flash 之类的 Twig 函数,需要时自己写 Twig\Extension\AbstractExtension 扩展:
<?php
declare(strict_types=1);
namespace App\twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('url', [$this, 'urlGenerator']),
new TwigFunction('old', [$this, 'oldInput']),
];
}
public function urlGenerator(string $path, array $params = []): string
{
// 生成 URL
return $path . (empty($params) ? '' : '?' . http_build_query($params));
}
public function oldInput(string $key, string $default = ''): string
{
// 获取旧输入
return (string) ($_SESSION['old'][$key] ?? $default);
}
}WebConfiguration 按 application.web.view 配置创建 TwigView 时, path、alias、globals、extension 之外的配置项会原样传给 new Twig\Environment($loader, $options)(如 cache、debug), globals 配置项注册全局模板变量——但没有注册 Twig 扩展的配置项。 需要自定义扩展时,自己装配 Twig\Environment 并提供 ViewInterface bean:
<?php
declare(strict_types=1);
namespace App\config;
use App\twig\AppExtension;
use DI\Attribute\Inject;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use kuiper\web\view\TwigView;
use kuiper\web\view\ViewInterface;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
#[Configuration]
class TwigConfiguration
{
#[Bean]
public function view(
#[Inject('application.web.view')] array $options,
#[Inject('application.base_path')] string $basePath
): ViewInterface {
$loader = new FilesystemLoader($options['path'] ?? $basePath . '/resources/views');
$twig = new Environment($loader, $options);
$twig->addExtension(new AppExtension());
foreach ((array) ($options['globals'] ?? []) as $name => $value) {
$twig->addGlobal((string) $name, $value);
}
$extension = $options['extension'] ?? null;
return new TwigView($twig, is_string($extension) ? $extension : null);
}
}完整的 Twig 模板示例
{# resources/views/users/list.html #}
{% extends "layout.html" %}
{% block title %}用户列表 - {{ parent() }}{% endblock %}
{% block content %}
<div class="container">
<h1>用户列表</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<a href="/users/{{ user.id }}">查看</a>
<a href="/users/{{ user.id }}/edit">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if totalPages > 1 %}
<nav aria-label="分页导航">
<ul class="pagination">
{% for i in 1..totalPages %}
<li class="{{ i == currentPage ? 'active' : '' }}">
<a href="/users?page={{ i }}">
{{ i }}
</a>
</li>
{% endfor %}
</ul>
</nav>
{% endif %}
</div>
{% endblock %}模板继承
创建基础模板 resources/views/layout.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My App{% endblock %}</title>
<link rel="stylesheet" href="/assets/css/style.css">
{% block head %}{% endblock %}
</head>
<body>
<nav class="navbar">
<a href="/">首页</a>
<a href="/users">用户</a>
</nav>
<main>
{% block content %}{% endblock %}
</main>
<footer>
{% block footer %}© 2024 My App{% endblock %}
</footer>
<script src="/assets/js/app.js"></script>
{% block scripts %}{% endblock %}
</body>
</html>子模板继承基础模板:
{% extends "layout.html" %}
{% block title %}用户列表 - {{ parent() }}{% endblock %}
{% block content %}
<h1>用户列表</h1>
<!-- 页面内容 -->
{% endblock %}在控制器中使用视图
视图的配置
WebConfiguration 已经提供了 ViewInterface,按 application.web.view 创建,一般不需要自己定义视图服务。
| 配置项 | PhpView | TwigView |
|---|---|---|
engine | php | twig |
path | 模板目录 | 模板目录,可以是目录数组 |
extension | 模板扩展名,默认 .php | 模板扩展名,默认为 null(模板名需自带后缀) |
alias | — | 命名空间到目录的映射,模板里用 @name/xxx 引用 |
globals | — | 全局模板变量 |
| 其它项 | — | 原样传给 Twig\Environment,如 cache、debug |
<?php
// config/config.php
return [
'application' => [
'web' => [
'view' => [
'engine' => 'twig',
'path' => __DIR__ . '/../resources/views',
'extension' => '.html',
'cache' => __DIR__ . '/../runtime/twig',
],
],
],
];配置了 'extension' => '.html' 后,模板名 home 会自动补全为 home.html。
在控制器中注入视图
除了自动注入,也可以在构造函数里直接注入 ViewInterface:
<?php
declare(strict_types=1);
namespace App\controller;
use App\service\UserService;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\view\ViewInterface;
use Psr\Http\Message\ResponseInterface;
#[Controller]
class UserController extends AbstractController
{
public function __construct(
private readonly ViewInterface $view,
private readonly UserService $userService,
) {
}
#[GetMapping('/users/{id}')]
public function show(int $id): ResponseInterface
{
$user = $this->userService->find($id);
$response = $this->getResponse()->withHeader('Content-Type', 'text/html; charset=utf-8');
$response->getBody()->write($this->view->render('users/show.php', ['user' => $user]));
return $response;
}
}控制器的操作方法接收路由参数,返回 ResponseInterface(或者不返回值,直接使用 $this->getResponse())。
视图最佳实践
1. 分离业务逻辑和视图
<?php
declare(strict_types=1);
namespace App\controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
// ✅ 好的做法:控制器准备数据,视图只负责渲染
final class UserListController extends AbstractController
{
use ControllerTrait;
#[GetMapping('/users')]
public function index(): ResponseInterface
{
$users = $this->userService->getAll(); // 业务逻辑
return $this->render('users/list.php', [
'users' => $users, // 只传递数据
]);
}
}{# 不好的做法:在模板中查询数据库 #}
{% for user in users %}
{{ user.name }}
{% endfor %}2. 使用模板继承
{# 好的做法:使用基础模板 #}
{% extends "layout.html" %}
{% block content %}{% endblock %}<!-- 不好的做法:每个模板都重复 HTML 结构 -->
<!DOCTYPE html>
<html>
<head>...</head>
<body>...</body>
</html>3. 始终转义输出
<?php // ✅ 好的做法:手动转义 ?>
<?= $__helpers::e($userInput) ?>
<?php // ❌ 不好的做法:不转义用户输入 ?>
<?= $userInput ?>{# ✅ 好的做法:Twig 默认自动转义,关闭时用 e 过滤器 #}
{{ userInput | e }}
{# ❌ 不好的做法:关闭自动转义后原样输出用户输入 #}
{{ userInput | raw }}4. 使用视图组件
<?php
declare(strict_types=1);
namespace App\component;
use kuiper\web\view\ViewInterface;
// 创建可重用的视图组件
final class UserCardComponent
{
public function __construct(
private readonly ViewInterface $view,
) {
}
public function render(array $user): string
{
return $this->view->render('components/user-card.php', [
'user' => $user,
]);
}
}<?php
declare(strict_types=1);
namespace App\controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
// 在控制器中使用视图组件
final class UserCardListController extends AbstractController
{
use ControllerTrait;
#[GetMapping('/users')]
public function index(): ResponseInterface
{
$users = $this->userService->getAll();
$cards = array_map(fn (array $user) => $this->userCard->render($user), $users);
return $this->render('users/index.php', [
'userCards' => implode("\n", $cards),
]);
}
}