Hyperf 视图引擎完全指南:基于 Blade 语法的 view-engine 组件深入解析

原创2026-10-08 19:32:161,652 阅读
文章标签:后端Web框架微服务RPC框架依赖注入服务注册发现配置中心并发编程API网关消息队列

Hyperf 视图引擎完全指南:基于 Blade 语法的 view-engine 组件深入解析

Hyperf 的 view-engine 组件是基于 Laravel Blade 模板引擎改写的高性能视图渲染组件,完整保留了原生 Blade 的模板继承、组件插槽、流程控制等语法,可无缝服务于 Hyperf 协程框架下的 MVC 开发场景。通过本文,你将掌握该组件的安装配置、模板继承与数据显示、流程控制指令、组件与插槽体系、视图命名空间及可选中间件的完整用法,并了解其底层的渲染链路与源码实现。

组件简介与安装

什么是 view-engine

Hyperf 官方文档对其的定义是:基于 Laravel blade 模板引擎改写,支持原始 blade 模板引擎的语法(见 docs/zh-cn/view-engine.md)。这意味着如果你已经熟悉 Laravel 的 Blade 模板,几乎可以零成本迁移到 Hyperf 项目中。

与其他流行的 PHP 模板引擎不同,Blade 并不限制在视图中使用原生 PHP 代码。所有 Blade 视图文件都会被编译成原生的 PHP 代码并缓存起来,除非文件被修改,否则不会重新编译。这种「编译 + 缓存」机制意味着 Blade 基本上不会给应用增加额外的运行时负担。

Blade 视图文件使用 .blade.php 作为文件扩展名,默认存放在 storage/view 目录,编译缓存默认存放在 runtime/view 目录。

安装组件

使用 Composer 安装:

composer require hyperf/view-engine

安装完成后,发布配置:

php bin/hyperf.php vendor:publish hyperf/view-engine

该命令会将组件自带的配置模板复制到 config/autoload/view.php。从源码角度看,这一发布动作由组件的 ConfigProvider.php 中的 publish 段定义:源文件为 src/view-engine/publish/view.php,目标位置为 BASE_PATH . '/config/autoload/view.php'。

配置详解

核心配置项

发布后的默认配置(以 src/view-engine/publish/view.php 为准)如下:

<?php
use Hyperf\View\Mode;
use Hyperf\ViewEngine\HyperfViewEngine;

return [
    'engine' => HyperfViewEngine::class,
    'mode' => Mode::SYNC,
    'config' => [
        'view_path' => BASE_PATH . '/storage/view/',
        'cache_path' => BASE_PATH . '/runtime/view/',
        'charset' => 'UTF-8',
    ],

    // Autoload components.
    'autoload' => [
        'classes' => [
            'App\View\Component\\',
        ],
        'components' => [
            'components.', // BASE_PATH . '/storage/view/components/'
        ],
    ],

    # Custom components.
    'components' => [
        // 'other-alert' => \Other\ViewComponent\Alert::class
    ],

    # View namespaces. (Used for packages)
    'namespaces' => [
        // 'admin' => BASE_PATH . '/storage/view/vendor/admin',
    ],
];

各配置项含义如下:

配置项 说明
engine 视图引擎实现类,默认 Hyperf\ViewEngine\HyperfViewEngine::class,负责将模板名与数据交给底层 Factory 渲染
mode 渲染模式,可选 Mode::SYNC(同步渲染)或 Mode::TASK(投递到 Task 进程渲染)
config.view_path 视图模板存放目录,默认 BASE_PATH/storage/view/
config.cache_path 编译缓存目录,默认 BASE_PATH/runtime/view/
config.charset 输出字符集,默认 UTF-8
autoload.classes 自动注册的类组件命名空间前缀
autoload.components 自动注册的匿名组件视图路径前缀
components 手动注册的组件别名映射(类名 => 组件类)
namespaces 视图命名空间(主要用于扩展包)

渲染模式:SYNC 与 TASK

官方文档特别提示:本组件推荐使用 SYNC 的渲染模式,可以有效减少进程间通信的损耗。渲染模式定义于 src/view/src/Mode.php:

class Mode
{
    public const TASK = 'task';

    public const SYNC = 'sync';
}
  • SYNC:在当前协程进程内直接同步渲染视图,无需额外的进程间通信,是推荐模式;
  • TASK:将渲染任务投递到 Task 进程执行,适用于需要与主进程隔离的特定场景,但会引入进程间通信开销。

组件与命名空间配置

components 用于注册自定义组件,例如:

'components' => [
    'alert' => \App\View\Component\Alert::class,
],

namespaces 用于为扩展包定义视图命名空间,例如:

'namespaces' => [
    'admin' => BASE_PATH . '/storage/view/vendor/admin',
],

更详细用法将在下文「组件与插槽」「视图命名空间」两节展开。

Blade 模板基础

模板继承

定义布局

大多数 Web 应用会在不同页面中使用相同的布局方式,可以很方便地定义单个 Blade 布局视图。例如 storage/view/layouts/app.blade.php:

<!-- Stored in storage/view/layouts/app.blade.php -->

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

@section 指令用于定义片段(Section)的内容,@yield 指令则用于显示片段的内容。

布局继承

定义子视图时,使用 @extends 指令指定要继承的布局,并通过 @section 指令向布局片段注入内容。例如 storage/view/child.blade.php:

<!-- Stored in storage/view/child.blade.php -->

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @parent

    <p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

这里 sidebar 片段利用 @parent 指令向布局的 sidebar 追加(而非覆盖)内容,渲染时 @parent 会被布局中的原内容替换。

注意与上一个示例的差异:此处的 sidebar 片段使用 @endsection 结尾,而布局中使用的是 @show。@endsection 仅定义片段,@show 则在定义的同时立即 yield 该片段。

@yield 指令还接受一个默认值作为第二个参数,若被 yield 的片段未定义,则渲染该默认值:

@yield('content', 'Hyperf')

Blade 视图可以用 Hyperf\ViewEngine\view 辅助函数返回。以下是一个完整的控制器示例:

<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use function Hyperf\ViewEngine\view;

#[AutoController(prefix: "view")]
class ViewController extends AbstractController
{
    public function child()
    {
        return (string) view('child');
    }
}

从源码层面看,view() 辅助函数定义于 src/view-engine/src/Functions.php:它会先从容器中取出 RenderInterface 获取 content-type 并设置到响应头,再从容器取出 FactoryInterface;当不传参数时返回 Factory 本身(便于链式调用),传入视图名时则调用 $factory->make($view, $data, $mergeData) 创建视图实例。

显示数据

你可以把变量置于花括号中以在视图中显示数据。例如给定如下路由:

use Hyperf\HttpServer\Router\Router;
use function Hyperf\ViewEngine\view;

Router::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});

视图中即可这样显示 name 变量:

Hello, {{ $name }}.

注意:Blade 的 {{ }} 语句会被 PHP 的 htmlspecialchars 函数自动转义,以防范 XSS 攻击。

不仅仅可以显示传递给视图的变量,你还可以在回显语句中放置任何 PHP 代码:

The current UNIX timestamp is {{ time() }}.

显示非转义字符

默认情况下 {{ }} 会自动转义。如果不想数据被转义,可使用如下语法:

Hello, {!! $name !!}.

在应用中显示用户提供的数据时请格外小心,请尽可能使用转义语法来防范 XSS 攻击。

渲染 JSON

有时需要向视图传递数组并渲染成 JSON 来初始化 JavaScript 变量。除了手动调用 json_encode:

<script>
    var app = <?php echo json_encode($array); ?>;
</script>

更推荐使用 @json Blade 指令,其参数与 PHP 的 json_encode 函数一致:

<script>
    var app = @json($array);

    var app = @json($array, JSON_PRETTY_PRINT);
</script>

使用 @json 指令时,应该只渲染已经存在的变量。Blade 模板基于正则表达式实现,如果尝试将复杂表达式传给 @json 指令,可能会导致无法预测的错误。

HTML 实体编码

默认情况下 Blade 会对 HTML 实体进行双重编码。如需禁用,可监听 BootApplication 事件并调用 Blade::withoutDoubleEncoding 方法:

<?php

declare(strict_types=1);

namespace App\Listener;

use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;
use Hyperf\ViewEngine\Blade;
use Psr\Container\ContainerInterface;

#[Listener]
class BladeWithoutDoubleEncodingListener implements ListenerInterface
{
    private ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            BootApplication::class
        ];
    }

    public function process(object $event)
    {
        Blade::withoutDoubleEncoding();
    }
}

这里的 Blade 类(见 src/view-engine/src/Blade.php)是一个静态门面(Facade):它通过 __callStatic 将静态调用委托给容器中的 CompilerInterface 实例,因此诸如 Blade::withoutDoubleEncoding()、Blade::compileString()、Blade::directive() 等方法实际作用于底层编译器对象。

Blade 与 JavaScript 框架

许多 JavaScript 框架也使用「花括号」标识浏览器端表达式。此时可以用 @ 符号告诉 Blade 保持原样:

<h1>Laravel</h1>

Hello, @{{ name }}.

这个例子中 @ 符号会被 Blade 移除,{{ name }} 表达式则原样保留,交给 JavaScript 模板渲染。@ 符号同样用于转义 Blade 指令本身:

{{-- Blade --}}
@@json()

<!-- HTML 输出 -->
@json()

如果模板中嵌入了大段 JavaScript 变量,可以把 HTML 包进 @verbatim 指令中,无需在每个回显语句前加 @:

@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

流程控制

Blade 为常见的 PHP 控制结构提供了简洁快捷的写法,同时保持与 PHP 相似的语法特性。

If 语句

使用 @if、@elseif、@else 和 @endif 构造 if 语句,功能与对应 PHP 语句完全一致:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

@unless 是 @if 的取反形式:

@unless (is_signed_in())
    You are not signed in.
@endunless

@isset 和 @empty 则是对应 PHP 函数的快捷方式:

@isset($records)
    // $records 已经定义但不为空
@endisset

@empty($records)
    // $records 为空……
@endempty

区块指令

@hasSection 判断区块是否有内容:

@hasSection('navigation')
    <div class="pull-right">
        @yield('navigation')
    </div>

    <div class="clearfix"></div>
@endif

@sectionMissing 判断区块是否没有内容:

@sectionMissing('navigation')
    <div class="pull-right">
        @include('default-navigation')
    </div>
@endif

环境指令

@production 判断应用是否处于生产环境:

@production
    // 生产环境特定内容……
@endproduction

@env 判断应用是否运行于指定环境(支持传数组匹配多个环境):

@env('staging')
    // 应用运行于「staging」环境……
@endenv

@env(['staging', 'production'])
    // 应用运行于「staging」环境或生产环境……
@endenv

Switch 语句

使用 @switch、@case、@break、@default 和 @endswitch 构造 Switch 语句:

@switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch

循环

Blade 提供与 PHP 循环结构功能相同的指令:

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile

循环中可以终止循环或跳过当前迭代:

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

也可以在指令的单独一行中声明条件语句:

@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

Loop 变量

循环内部可以使用 $loop 变量获取当前迭代的索引、是否首次/末次等信息:

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

嵌套循环中,可通过 $loop->parent 访问父级循环:

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

$loop 变量包含的属性如下:

属性 备注
$loop->index 当前迭代的索引(从 0 开始)。
$loop->iteration 当前循环的迭代次数(从 1 开始)。
$loop->remaining 循环剩余的迭代次数。
$loop->count 被迭代的数组的元素个数。
$loop->first 当前迭代是否是循环的首次迭代。
$loop->last 当前迭代是否是循环的末次迭代。
$loop->even 当前循环的迭代次数是否是偶数。
$loop->odd 当前循环的迭代次数是否是奇数。
$loop->depth 当前循环的嵌套深度。
$loop->parent 嵌套循环中的父级循环。

注释

Blade 注释不会被包含在应用返回的 HTML 中:

{{-- This comment will not be present in the rendered HTML --}}

PHP 代码块

可以使用 @php 指令在模板中执行原生 PHP 代码块:

@php
    //
@endphp

尽管 Blade 提供了这个功能,频繁使用可能使模板中嵌入过多逻辑。

@once 指令

@once 指令定义模板的一部分内容,这部分内容在每一个渲染周期中只会被计算一次。它常与「堆栈」配合使用——例如在循环中渲染某个组件时,只在首次渲染时向页面头部推送一段 JavaScript:

@once
    @push('scripts')
        <script>
            // 您自定义的 JavaScript 代码
        </script>
    @endpush
@endonce

组件及插槽

组件和插槽的作用与片段(Section)和布局(Layout)类似,但使用起来更加方便。Hyperf 支持两种编写组件的方法:基于类的组件和匿名组件。

类组件

创建一个继承 \Hyperf\ViewEngine\Component\Component::class 的类即可定义类组件。以下是一个简单的 Alert 组件:

<?php
namespace App\View\Component;
use Hyperf\ViewEngine\Component\Component;
use function Hyperf\ViewEngine\view;
class Alert extends Component
{
    public $type;
    public $message;
    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }
    public function render()
    {
        return view('components.alert');
    }
}

对应的视图模板 storage/view/components/alert.blade.php:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>

手动注册组件

在 config/autoload/view.php 中注册:

<?php
return [
    // ...
    'components' => [
        'alert' => \App\View\Component\Alert::class,
    ],
];

或者在扩展包的 ConfigProvider 中注册:

<?php
class ConfigProvider
{
    public function __invoke()
    {
        return [
            // ...others config
            'view' => [
                // ...others config
                'components' => [
                    'package-alert' => \App\View\Component\Alert::class,
                ],
            ],
        ];
    }
}

注册后即可通过 HTML 标签别名使用组件:

<x-alert/>
<x-package-alert/>

值得说明的是,dynamic-component 组件正是通过 ConfigProvider.php 中 view.components 配置注册的内置组件(映射到 Hyperf\ViewEngine\Component\DynamicComponent::class)。

组件传参

可以使用 HTML 属性向组件传递数据。普通值通过简单的 HTML 属性传递,PHP 表达式及变量通过以 : 为前缀的属性传递:

<x-alert type="error" :message="$message"/>

注意:可以在组件类的构造函数中定义组件所需的数据。组件类中的所有公共属性都会自动传递给组件视图,无需通过 render 方法传递。渲染组件时,可以通过变量名称获取组件类公共属性的内容。

组件方法

除了公共属性外,组件视图中还可以执行组件类上的任何公共方法。例如组件具有 isSelected 方法:

    /**
     * 判断给定选项是否为当前选项
     *
     * @param  string  $option
     * @return bool
     */
    public function isSelected($option)
    {
        return $option === $this->selected;
    }

可以通过调用与方法名称相同的变量来执行该方法:

    <option {{ $isSelected($value) ? 'selected="selected"' : '' }} value="{{ $value }}">
        {{ $label }}
    </option>

附加依赖项

如果组件需要依赖其他类,应在组件所有数据属性之前列出它们,它们会被容器自动注入:

    use App\AlertCreator;
    /**
     * 创建组件实例
     *
     * @param  \App\AlertCreator  $creator
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct(AlertCreator $creator, $type, $message)
    {
        $this->creator = $creator;
        $this->type = $type;
        $this->message = $message;
    }

管理属性

有时需要指定一些非数据性的 HTML 属性(如 class),并希望它们被传递到组件模板的根元素。例如:

    <x-alert type="error" :message="$message" class="mt-4"/>

所有不属于组件构造函数的属性都会自动添加到组件的「属性包」中,通过 $attributes 变量传递给组件视图。输出该变量即可呈现所有属性:

    <div {{ $attributes }}>
        <!-- 组件内容 -->
    </div>

获取属性

使用 get() 方法获取特定属性值,第一个参数为属性名称,第二个参数为默认值:

    <div class="{{ $attributes->get("class", "default") }}">
        <!-- 组件内容 -->
    </div>

检测属性

使用 has() 方法检测属性是否存在,返回布尔值:

    @if($attributes->has("class"))
        <div class="{{ $attributes->get("class") }}">
            <!-- 组件内容 -->
        </div>
    @endif

合并属性

有时需要为属性指定默认值或将其他值合并到组件的某些属性中,可使用属性包的 merge 方法:

    <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
        {{ $message }}
    </div>

假设这样使用组件:

    <x-alert type="error" :message="$message" class="mb-4"/>

最终呈现的 HTML 为:

    <div class="alert alert-error mb-4">
        <!-- $message 变量的内容 -->
    </div>

默认情况下 merge() 只会合并 class 属性,其他属性直接覆盖。例如:

// 定义
<div {{ $attributes->merge(['class' => 'alert alert-'.$type, 'other-attr' => 'foo']) }}>{{ $message }}</div>
// 使用
<x-alert type="error" :message="$message" class="mb-4" other-attr="bar"/>
// 呈现
<div class="alert alert-error mb-4" other-attr="bar"><!-- $message 变量的内容 --></div>

如需将 other-attr 也一并合并,可在 merge() 方法中添加第二个参数 true:

// 定义
<div {{ $attributes->merge(['class' => 'alert alert-'.$type, 'other-attr' => 'foo'], true) }}>{{ $message }}</div>
// 使用
<x-alert type="error" :message="$message" class="mb-4" other-attr="bar"/>
// 呈现
<div class="alert alert-error mb-4" other-attr="foo bar"><!-- $message 变量的内容 --></div>

插槽

通常需要通过 slots 向组件传递附加内容。假设 alert 组件模板如下:

    <!-- /storage/view/components/alert.blade.php -->

    <div class="alert alert-danger">
        {{ $slot }}
    </div>

通过向组件注入内容即可传递到 $slot:

    <x-alert>
        <strong>Whoops!</strong> Something went wrong!
    </x-alert>

有时组件需要在内部不同位置放置多个插槽。修改 alert 组件以允许注入 title:

    <!-- /storage/view/components/alert.blade.php -->

    <span class="alert-title">{{ $title }}</span>

    <div class="alert alert-danger">
        {{ $slot }}
    </div>

使用 x-slot 标签定义命名插槽内容,不在 x-slot 中的其他内容都会传递给 $slot:

    <x-alert>
        <x-slot name="title">
            Server Error
        </x-slot>

        <strong>Whoops!</strong> Something went wrong!
    </x-alert>

内联组件

对于小型组件,管理类与视图模板可能很麻烦,可以直接从 render 方法返回组件内容:

    public function render()
    {
        return <<<'blade'
            <div class="alert alert-danger">
                {{ $slot }}
            </div>
        blade;
    }

匿名组件

匿名组件通过单个视图文件管理组件,不需要关联类。只需将 Blade 模板置于 /storage/view/components 目录下。例如在 /storage/view/components/alert.blade.php 中定义组件后:

    <x-alert/>

如果组件位于 components 目录的子目录中,使用 . 字符指定路径。例如组件定义在 /storage/view/components/inputs/button.blade.php:

    <x-inputs.button/>

匿名组件数据及属性

由于匿名组件没有关联类,需要区分哪些属性作为数据变量、哪些放入属性包。在模板顶层使用 @props 指令指定数据变量,其他属性通过属性包提供。如需默认值,将属性名作为数组键、默认值作为数组值:

    <!-- /storage/view/components/alert.blade.php -->

    @props(['type' => 'info', 'message'])

    <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
        {{ $message }}
    </div>

动态组件

有时需要渲染的组件在运行前未知,可使用内置的 dynamic-component 组件基于值或变量渲染:

    <x-dynamic-component :component="$componentName" class="mt-4" />

组件自动加载

默认情况下,App\View\Component\ 命名空间下的类组件及 components. 路径下的匿名组件会自动注册(对应配置中的 autoload.classes 与 autoload.components)。你也可以通过配置文件修改:

return [
    // ...
    'autoload' => [
        'classes' => ['App\\Other\\Component\\', 'App\\Another\\Component\\'],
        'components' => ['package::components.', 'components.'],
    ],
];

视图命名空间

通过定义视图命名空间,可以方便地在扩展包中使用视图文件,只需在 ConfigProvider 中添加一行配置:

<?php
class ConfigProvider
{
    public function __invoke()
    {
        return [
            // ...others config
            'view' => [
                // ...others config
                'namespaces' => [
                    'package-name' => __DIR__ . '/../views',
                ],
            ],
        ];
    }
}

安装扩展包之后,可以通过在项目的 /storage/view/vendor/package-name 中定义相同路径的视图文件,来覆盖扩展包中的视图。这一机制在 Factory.php 中有对应的实现支撑:Factory 通过 FinderInterface 查找视图文件,并提供 addNamespace、prependNamespace、replaceNamespace 等方法动态管理命名空间与路径的映射。

可选中间件

view-engine 提供了两个可选的 HTTP 中间件,均位于 Hyperf\ViewEngine\Http\Middleware 命名空间:

  • ShareErrorsFromSession::class(源码见 ShareErrorsFromSession.php):自动将 session 中的 errors 共享给视图,依赖 hyperf/session 组件;
  • ValidationExceptionHandle::class(源码见 ValidationExceptionHandle.php):自动捕捉 validation 中的异常并加入到 session 中,依赖 hyperf/session 和 hyperf/validation 组件。

将中间件注册到对应的路由或全局中间件配置中即可启用。配合 Factory 构造函数中默认 share('errors', new ViewErrorBag()) 的行为(见 Factory.php),视图内始终可以安全访问 $errors 变量。

其他命令

自动安装 view-engine、translation 和 validation 组件相关配置:

php bin/hyperf.php view:publish

该命令由 ViewPublishCommand.php 实现:其签名为 view:publish {--f|force},执行时会依次调用 vendor:publish 发布 hyperf/view-engine、hyperf/session、hyperf/validation、hyperf/translation 的配置。

另外,组件还注册了 GenerateViewCacheCommand(见 ConfigProvider.php 的 commands 列表),用于预生成视图编译缓存,可以推断其用途是在部署阶段提前编译全部模板,避免运行时首次访问产生编译延迟。

源码视角:一次视图渲染的完整链路

为了更深入地理解组件工作原理,可以从源码层面梳理一次渲染的调用链:

  1. 业务代码调用辅助函数 view('child')(Functions.php),它会设置响应的 content-type,并从容器取出 FactoryInterface(容器绑定见 ConfigProvider.php,默认实现为 Hyperf\ViewEngine\Factory);
  2. Factory::make($view, $data) 通过 FinderInterface 定位模板文件的物理路径,再根据扩展名(blade.php、php、css、html 等)解析出对应的渲染引擎(扩展名映射表定义于 Factory.php);
  3. 模板编译由 BladeCompiler 完成——Blade 门面将 compileString、directive、withoutDoubleEncoding 等静态调用委托给容器中的 CompilerInterface(见 Blade.php);
  4. 当配置的引擎为 HyperfViewEngine 时(HyperfViewEngine.php),其 render() 方法会从容器取出 FactoryInterface,执行 $factory->make($template, $data)->render() 得到最终 HTML 字符串。

整套设计将「模板查找 → 编译缓存 → 引擎解析 → 数据注入」拆分为多个可替换的接口(FactoryInterface、FinderInterface、CompilerInterface、EngineResolverInterface),既保证了与 Laravel Blade 语法的高度兼容,也充分利用了 Hyperf 的依赖注入容器与协程环境特性。

总结

view-engine 组件将 Laravel Blade 的成熟模板语法完整带入了 Hyperf 协程框架:模板继承、数据显示与 XSS 防护、完整的流程控制指令、$loop 循环变量、类组件与匿名组件、插槽、属性包、视图命名空间、可选中间件以及配套命令,构成了一个开箱即用的完整视图层解决方案。建议生产环境使用 SYNC 渲染模式以降低进程间通信开销,并利用 view:publish 命令一键补齐 session、validation、translation 等关联配置。

登录后查看全文
hyperf