安装
hyperf提供视图组件包含多种末班引擎,Blade 、 Smarty 、 Twig 、 Plates 和 ThinkTemplate,这里以blade组件为例。
# docker进入到容器中执行composer命令,安装view组件
composer require hyperf/view
安装 Blade 引擎
composer require hyperf/view-engine
在config/autoload/下创建view.php作为配置文件
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
use Hyperf\View\Mode;
use Hyperf\ViewEngine\HyperfViewEngine;
return [
'engine' => HyperfViewEngine::class,
# 官网推荐使用TASK模式,其他模式有
'mode' => Mode::TASK,
'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',
],
];
安装task组件
composer require hyperf/task
在config/autoload/server.php文件中增加以下配置
'settings' => [
// Task Worker 数量,根据您的服务器配置而配置适当的数量
'task_worker_num' => 8,
// 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况
'task_enable_coroutine' => false,
],
'callbacks' => [
// Task callbacks
Event::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'],
Event::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'],
],
浏览器尝试访问
控制器文件部分代码如下
use Hyperf\View\RenderInterface;
public function viewer(RequestInterface $request, RenderInterface $render)
{
return $render->render('index', ['name' => 'Hyperf']);
}
创建视图文件 storage/view/index.blade.php
<html>
<head>
<title>test for view !</title>
</head>
<body>
<div class="container">
{{ $name }}
</div>
</body>
</html>
浏览器访问,页面正常显示。