Hyperf view-engine 组件实战指南:基于 Blade 语法的协程视图引擎完全解析

原创2026-10-08 23:00:401,433 阅读
文章标签:后端微服务RPC框架Web框架

Hyperf view-engine 组件实战指南:基于 Blade 语法的协程视图引擎完全解析

导读

hyperf/view-engine 是 Hyperf 框架中基于 Laravel Blade 模板引擎改写的高性能视图组件,完整兼容原始 Blade 语法,让习惯了 Laravel 的开发者可以在 Swoole 协程环境下无缝迁移模板工程。本文将以官方文档为主线,结合仓库源码逐项解析其安装配置、模板继承、数据渲染、流程控制、组件与插槽、视图命名空间及可选中间件,帮助你掌握从 view() 辅助函数到组件自动加载的完整实战能力。

安装与配置

安装组件

通过 Composer 安装:

composer require hyperf/view-engine

组件要求 PHP >= 8.2,并依赖 hyperf/view、hyperf/di、hyperf/event、hyperf/support 等核心组件(见 composer.json)。

生成配置

执行发布命令,将默认配置发布到 config/autoload/view.php:

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

默认配置如下:

return [
    'engine' => Hyperf\ViewEngine\HyperfViewEngine::class,
    'mode' => Hyperf\View\Mode::SYNC,
    'config' => [
        'view_path' => BASE_PATH . '/storage/view/',
        'cache_path' => BASE_PATH . '/runtime/view/',
    ],

    # 自定義組件註冊
    'components' => [
        // 'alert' => \App\View\Components\Alert::class
    ],

    # 視圖命名空間 (主要用於擴展包中)
    'namespaces' => [
        // 'admin' => BASE_PATH . '/storage/view/vendor/admin',
    ],
];

建议:本组件推荐使用 SYNC 渲染模式,可以有效减少进程间通信的损耗。

查看仓库实际发布的配置文件 src/view-engine/publish/view.php,可以发现它还额外包含两个关键项:

  • config.charset:默认 UTF-8,用于指定渲染输出的字符集;
  • autoload:组件自动加载配置,默认注册 App\View\Component\ 命名空间类组件,以及 components. 路径下的匿名组件(即 BASE_PATH . '/storage/view/components/')。

配置项如何生效

从源码看,配置通过 ConfigProvider.php 完成依赖注入与发布:

  • FactoryInterface::class => Factory::class
  • EngineResolverInterface::class => EngineResolverFactory::class
  • FinderInterface::class => FinderFactory::class
  • CompilerInterface::class => CompilerFactory::class
  • 注册了两个命令:ViewPublishCommand、GenerateViewCacheCommand
  • 内置注册 dynamic-component 组件

而在 CompilerFactory.php 中,components 与 autoload 配置被逐一注册到 BladeCompiler 上,这正是「手动注册组件」与「组件自动加载」配置生效的底层机制。

mode 与 engine 的配合则由 HyperfViewEngine::render() 完成:从容器中取出 FactoryInterface,调用 make($template, $data)->render() 渲染并返回字符串(见 HyperfViewEngine.php)。

快速上手:返回视图

view() 辅助函数定义在 Functions.php,其签名兼容 view($view = null, $data = [], $mergeData = []):当传入视图名时返回视图实例,不传参数时返回 FactoryInterface 工厂本身;同时会根据 RenderInterface::getContentType() 自动设置响应的 content-type 头。

在控制器中返回视图:

<?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');
    }
}

也可以在路由闭包中直接使用:

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

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

Blade 模板基础

Blade 是 Laravel 提供的一个简单而又强大的模板引擎。与其他流行的 PHP 模板引擎不同,Blade 并不限制你在视图中使用原生 PHP 代码。所有 Blade 视图文件都将被编译成原生的 PHP 代码并缓存起来,除非它被修改,否则不会重新编译,这意味着 Blade 基本上不会给你的应用增加任何负担。

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

从 Factory.php 的源码可以看到视图引擎按扩展名解析:

protected array $extensions = [
    'blade.php' => 'blade',
    'php' => 'php',
    'css' => 'file',
    'html' => 'file',
];

即 .blade.php 走 Blade 编译器、.php 走原生 PHP 引擎、.css 与 .html 走文件引擎,渲染管线清晰可扩展。

模板继承

定义布局

大多数 Web 应用会在不同页面中使用相同的布局方式,可以方便地定义单个 Blade 布局视图:

<!-- 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>

这里包含常见的 HTML 标签,其中 @section 指令定义了「片段」(Section)的内容,而 @yield 指令则用来显示片段的内容。

布局继承

定义子视图时,使用 @extends 指令指定子视图要「继承」的视图;继承布局的子视图可以使用 @section 指令向布局片段注入内容,这些内容最终由布局中的 @yield 指令控制显示:

<!-- 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')

显示数据

把变量置于花括号中即可在视图中显示数据:

Hello, {{ $name }}.

Blade 的 {{ }} 语句将被 PHP 的 htmlspecialchars 函数自动转义,以防 XSS 攻击。

不仅可显示传递给视图的变量,也可以输出任何 PHP 函数的结果,你可以在 Blade 模板的回显语句中放置任何 PHP 代码:

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

显示非转义字符

如果你不想数据被转义,可使用 {!! !!} 语法:

Hello, {!! $name !!}.

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

渲染 JSON

为了初始化一个 JavaScript 变量,可能会向视图传递数组并渲染成 JSON:

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

也可以使用 @json 指令代替手动调用 json_encode,参数与 PHP 的 json_encode 函数一致:

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

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

使用 @json 指令时,应该只渲染已经存在的变量为 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 是一个静态代理门面,其 __callStatic 会从容器解析 CompilerInterface 并转发调用(见 Blade.php),因此 Blade::withoutDoubleEncoding()、Blade::directive()、Blade::component() 等方法均可静态调用。

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

对应测试可参考 BladeVerbatimTest.php。

流程控制

除了模板继承和显示数据,Blade 还为常见 PHP 控制结构提供了便捷的快捷方式,与 PHP 原生语法保持相似特性。

If 语句

@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 指令:

@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($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 嵌套循环中的父级循环。

这些行为的实现可参考 ManagesLoops.php 与对应测试 BladeLoopsTest.php。

注释

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

其「只渲染一次」的状态记录在 Factory 的 $renderedOnce 数组中(见 Factory.php 的 hasRenderedOnce / markAsRenderedOnce 方法)。

组件及插槽

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

类组件

创建一个继承 \Hyperf\ViewEngine\Component\Component::class 的类来定义类组件,以 Alert 组件为例:

app/View/Component/Alert.php

<?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/>

显示组件

Blade 组件标签以 x- 开头,后接组件名称:

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

组件传参

普通值可通过简单 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>

默认情况下只合并 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>

属性包的底层实现在 ComponentAttributeBag.php,测试覆盖见 BladeComponentsTest.php。

插槽

通过 slots 向组件传递附加内容。假设 alert 组件具有以下标记:

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

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

通过向组件注入内容的方式传递到插槽:

    <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" />

该组件由 DynamicComponent.php 实现,并在 ConfigProvider.php 中作为内置组件注册。

组件自动加载

默认情况下,App\View\Component\ 命名空间及 components. 路径下的组件会自动注册,也可通过配置文件修改(对应 autoload 配置项,最终在 CompilerFactory.php 中通过 setComponentAutoload 生效):

config/autoload/view.php

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 中定义相同路径的视图文件,来覆盖扩展包中的视图。命名空间的查找与提示(hint)逻辑由 Finder.php 提供。

可选中间件

ShareErrorsFromSession

Hyperf\ViewEngine\Http\Middleware\ShareErrorsFromSession::class:自动将 session 中的 errors 共享给视图,依赖 hyperf/session 组件。

ValidationExceptionHandle

Hyperf\ViewEngine\Http\Middleware\ValidationExceptionHandle::class:自动捕捉 validation 中的异常并加入到 session 中,依赖 hyperf/session 和 hyperf/validation 组件。

从 ValidationExceptionHandle.php 的实现可见:该中间件捕获 ValidationException,将其错误信息通过 withErrors() 以 ViewErrorBag 的形式 flash 到 session,然后重定向到 session->previousUrl();非验证异常则原样抛出。

两个中间件依赖的组件在 composer.json 的 suggest 中均有标注:

  • hyperf/session:ShareErrorsFromSession 与 ValidationExceptionHandle 均需要
  • hyperf/validation:ShareErrorsFromSession 与 ValidationExceptionHandle 需要

其他命令

view:publish

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

php bin/hyperf.php view:publish

命令实现见 ViewPublishCommand.php:签名支持 {--f|force} 选项,它会发布 hyperf/view-engine 的配置,并依次发布 hyperf/session、hyperf/validation、hyperf/translation 三个关联组件的配置。

gen:view-engine-cache

除文档外,仓库还提供了预编译视图缓存命令(见 GenerateViewCacheCommand.php):

php bin/hyperf.php gen:view-engine-cache

该命令会读取 view.config.view_path 目录下所有 *.blade.php 文件,通过 CompilerInterface 预编译生成缓存;若未配置 view.config.view_path 会输出警告提示。

小结

Hyperf 的 view-engine 组件在完整保留 Blade 模板继承、数据渲染、流程控制、组件插槽等经典能力的同时,深度融入了 Hyperf 的依赖注入容器与协程架构:view() 辅助函数自动设置响应头,SYNC 模式减少进程间通信损耗,组件与命名空间可借助 ConfigProvider 完成包级注册,view:publish 与 gen:view-engine-cache 两条命令则分别覆盖了配置初始化与缓存预热场景。你可以直接在 storage/view 目录编写 .blade.php 模板,并结合 x- 组件标签与 $attributes 属性包构建出可复用、可维护的视图体系。

登录后查看全文
hyperf