当前位置: 首页 > news >正文

学习路之PHP--easyswoole使用视图和模板

学习路之PHP--easyswoole使用视图和模板

  • 一、安装依赖插件
  • 二、 实现渲染引擎
  • 三、注册渲染引擎
  • 四、测试调用写的模板
  • 五、优化
  • 六、最后补充

一、安装依赖插件

composer require easyswoole/template:1.1.*
composer require topthink/think-template

相关版本:

        "easyswoole/easyswoole": "3.3.x","easyswoole/orm": "^1.5","easyswoole/template": "1.1.*","topthink/think-template": "^2.0"

二、 实现渲染引擎

在 App 目录下 新建 System 目录 存放 渲染引擎实现的代码 ThinkTemplate.php

<?php
namespace App\System;use EasySwoole\Template\RenderInterface;
use think\facade\Template;class ThinkTemplate implements RenderInterface
{// tp模板类对象private $_topThinkTemplate;public function __construct(){$temp_dir = sys_get_temp_dir();$config = ['view_path' => EASYSWOOLE_ROOT . '/App/HttpTemplate/', // 模板存放文件夹根目录'cache_path' => $temp_dir, // 模板文件缓存目录'view_suffix' => 'html' // 模板文件后缀];$this->_topThinkTemplate = new \think\Template($config);}public function afterRender(?string $result, string $template, array $data = [], array $options = []){}// 当模板解析出现异常时调用public function onException(\Throwable $throwable): string{$msg = $throwable->getMessage() . " is file " . $throwable->getFile() . ' of line' . $throwable->getLine();return $msg;}// 渲染逻辑实现public function render(string $template, array $data = [], array $options = []): ?string{foreach ($data as $k => $v) {$this->_topThinkTemplate->assign([$k => $v]);}// Tp 模板渲染函数都是直接输出 需要打开缓冲区将输出写入变量中 然后渲染的结果ob_start();$this->_topThinkTemplate->fetch($template);$content = ob_get_contents();ob_end_clean();return $content;}
}

由于版本问题:报错
在这里插入图片描述

<?php
namespace App\System;use EasySwoole\Template\RenderInterface;
use think\facade\Template;class ThinkTemplate implements RenderInterface
{// tp模板类对象private $_topThinkTemplate;public function __construct(){$temp_dir = sys_get_temp_dir();$config = ['view_path' => EASYSWOOLE_ROOT . '/App/HttpTemplate/', // 模板存放文件夹根目录'cache_path' => $temp_dir, // 模板文件缓存目录'view_suffix' => 'html' // 模板文件后缀];$this->_topThinkTemplate = new \think\Template($config);}public function afterRender(?string $result, string $template, array $data = [], array $options = []){}// 当模板解析出现异常时调用// public function onException(\Throwable $throwable): string// {//     $msg = $throwable->getMessage() . " is file " . $throwable->getFile() . ' of line' . $throwable->getLine();//     return $msg;// }// 渲染逻辑实现// public function render(string $template, array $data = [], array $options = []): ?string// {//     foreach ($data as $k => $v) {//         $this->_topThinkTemplate->assign([$k => $v]);//     }//     // Tp 模板渲染函数都是直接输出 需要打开缓冲区将输出写入变量中 然后渲染的结果//     ob_start();//     $this->_topThinkTemplate->fetch($template);//     $content = ob_get_contents();//     ob_end_clean();//     return $content;// }public function render(string $template, ?array $data = null, ?array $options = null): ?string{// return "your template is {$template} and data is " . json_encode($data);foreach ($data as $k => $v) {$this->_topThinkTemplate->assign([$k => $v]);}// Tp 模板渲染函数都是直接输出 需要打开缓冲区将输出写入变量中 然后渲染的结果ob_start();$this->_topThinkTemplate->fetch($template);$content = ob_get_contents();ob_end_clean();return $content;}public function onException(\Throwable $throwable, $arg): string{// return $throwable->getTraceAsString();$msg = $throwable->getMessage() . " is file " . $throwable->getFile() . ' of line' . $throwable->getLine();return $msg;}
}

三、注册渲染引擎

需要对模板引擎进行实例化并且注入到EasySwoole 的视图中 在项目根目录 EasySwooleEvent.php 中 mainServerCreate 事件函数中进行注入代码如下

use App\System\ThinkTemplate;
use EasySwoole\Template\Render; use
EasySwoole\Template\RenderInterface;

// 设置Http服务模板类
Render::getInstance()->getConfig()->setRender(new ThinkTemplate());
Render::getInstance()->getConfig()->setTempDir(EASYSWOOLE_TEMP_DIR);
Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());

四、测试调用写的模板

在App目录下创建 HttpTemplate 目录 PS:之前在 ThinkTemplate.php 文件中设置的路径

创建文件 /App/HttpTemplate/Admin/Index/index.html 路径与模块 控制器 响应函数相对应 你也可以按照自己的喜欢来

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>tao</title>
</head>
<body>
<ul>{foreach $user_list as $key => $val}<li>{$key} => {$val}</li>{/foreach}
</ul>
</body>
</html>

在 App\HttpController\Admin 中调用

use EasySwoole\Template\Render;
public function index(){$user_list = ['1', '2', '3', '4', '5'];$this->response()->write(Render::getInstance()->render('Index/index', ['user_list' => $user_list]));}

在这里插入图片描述
在这里插入图片描述

五、优化

这样的模板传值非常麻烦有木有 还必须要放在一个数组中一次性传给 Render 对象 我们可以将操作封装到基类控制器 实现类似于TP框架的操作 代码如下

<?php
/*** 基础控制器类*/
namespace App\HttpController;use EasySwoole\Template\Render;abstract class Controller extends \EasySwoole\Http\AbstractInterface\Controller
{public $template_data = [];public function assign($name, $value) {$this->template_data[$name] = $value;}public function fetch($template_name) {return Render::getInstance()->render($template_name, $this->template_data);}
}

这样我们就可以使用TP的风格进行模板传值了 效果和上面时一样的 PS:暂时需要指定模板的路径

function index(){$user_list = ['1', '2', '3', '4', '5'];$this->assign('user_list', $user_list);$this->response()->write($this->fetch('Index/index'));}

六、最后补充

EasySwooleEvent.php

<?php
namespace EasySwoole\EasySwoole;use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use App\Process\HotReload;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Connection;
use App\System\ThinkTemplate;
use EasySwoole\Template\Render;
use EasySwoole\Template\RenderInterface;class EasySwooleEvent implements Event
{public static function initialize(){// TODO: Implement initialize() method.date_default_timezone_set('Asia/Shanghai');$config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));DbManager::getInstance()->addConnection(new Connection($config));}public static function mainServerCreate(EventRegister $register){// TODO: Implement mainServerCreate() method.$swooleServer = ServerManager::getInstance()->getSwooleServer();$swooleServer->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());Render::getInstance()->getConfig()->setRender(new ThinkTemplate());Render::getInstance()->getConfig()->setTempDir(EASYSWOOLE_TEMP_DIR);Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());}public static function onRequest(Request $request, Response $response): bool{// TODO: Implement onRequest() method.return true;}public static function afterRequest(Request $request, Response $response): void{// TODO: Implement afterAction() method.}
}

App\System\ThinkTemplate.php

<?php
namespace App\System;use EasySwoole\Template\RenderInterface;
use think\facade\Template;class ThinkTemplate implements RenderInterface
{// tp模板类对象private $_topThinkTemplate;public function __construct(){$temp_dir = sys_get_temp_dir();$config = ['view_path' => EASYSWOOLE_ROOT . '/App/HttpTemplate/', // 模板存放文件夹根目录'cache_path' => $temp_dir, // 模板文件缓存目录'view_suffix' => 'html' // 模板文件后缀];$this->_topThinkTemplate = new \think\Template($config);}public function afterRender(?string $result, string $template, array $data = [], array $options = []){}// 当模板解析出现异常时调用// public function onException(\Throwable $throwable): string// {//     $msg = $throwable->getMessage() . " is file " . $throwable->getFile() . ' of line' . $throwable->getLine();//     return $msg;// }// 渲染逻辑实现// public function render(string $template, array $data = [], array $options = []): ?string// {//     foreach ($data as $k => $v) {//         $this->_topThinkTemplate->assign([$k => $v]);//     }//     // Tp 模板渲染函数都是直接输出 需要打开缓冲区将输出写入变量中 然后渲染的结果//     ob_start();//     $this->_topThinkTemplate->fetch($template);//     $content = ob_get_contents();//     ob_end_clean();//     return $content;// }public function render(string $template, ?array $data = null, ?array $options = null): ?string{// return "your template is {$template} and data is " . json_encode($data);foreach ($data as $k => $v) {$this->_topThinkTemplate->assign([$k => $v]);}// Tp 模板渲染函数都是直接输出 需要打开缓冲区将输出写入变量中 然后渲染的结果ob_start();$this->_topThinkTemplate->fetch($template);$content = ob_get_contents();ob_end_clean();return $content;}public function onException(\Throwable $throwable, $arg): string{// return $throwable->getTraceAsString();$msg = $throwable->getMessage() . " is file " . $throwable->getFile() . ' of line' . $throwable->getLine();return $msg;}
}

App\HttpController\Index.php

<?phpnamespace App\HttpController;use EasySwoole\Template\Render;class Index extends BaseController
{/*** */public function index(){$user_list = ['1', '2', '3', '4', '5'];$this->assign('user_list', $user_list);$this->response()->write($this->fetch('Index/index'));}}

App\HttpController\BaseController.php

<?php
/*** 基础控制器类*/
namespace App\HttpController;use EasySwoole\Template\Render;abstract class BaseController extends \EasySwoole\Http\AbstractInterface\Controller
{public $template_data = [];public function assign($name, $value) {$this->template_data[$name] = $value;}public function fetch($template_name) {return Render::getInstance()->render($template_name, $this->template_data);}
}

App\HttpTemplate\Index\index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>视频模板测试</title>
</head>
<body>
<ul>{foreach $user_list as $key => $val}<li>{$key} => {$val}</li>{/foreach}
</ul>
</body>
</html>
http://www.lqws.cn/news/90649.html

相关文章:

  • 大语言模型评测体系全解析(上篇):基础框架与综合评测平台
  • 用户管理页面(解决toggleRowSelection在dialog用不了的隐患,包含el-table的plus版本的组件)
  • 剑指offer15_数值的整数次方
  • Elasticsearch | 如何将修改已有的索引字段类型并迁移数据
  • 云原生周刊:探索 Gateway API v1.3.0
  • 点击启动「高效模式」:大腾智能 CAD 重构研发设计生产力
  • Go 为何天生适合云原生?
  • 项目前置知识——不定参以及设计模式
  • MYSQL索引详解
  • 平台化 LIMS 系统架构 跨行业协同与资源共享的实现路径
  • Ubuntu 22.04 安装 Nacos 记录
  • ubuntu 20.04挂载固态硬盘
  • Ubuntu22.04安装MinkowskiEngine
  • 安装和配置 Nginx 和 Mysql —— 一步一步配置 Ubuntu Server 的 NodeJS 服务器详细实录6
  • 解决 Ubuntu 20.04 虚拟机中 catkin_make 编译卡死问题
  • seafile:ubuntu搭建社区版seafile12.0
  • Starrocks Full GC日志分析
  • Stone 3D新版本发布,添加玩家控制和生物模拟等组件,增强路径编辑功能,优化材质编辑
  • 无人机避障——感知部分(Ubuntu 20.04 复现Vins Fusion跑数据集)胎教级教程
  • 网络安全厂商F5推出AI Gateway,化解大模型应用风险
  • RequestRateLimiterGatewayFilterFactory
  • 大数据 ETL 工具 Sqoop 深度解析与实战指南
  • 深入解析 Flask 命令行工具与 flask run命令的使用
  • 生产环境中安装和配置 Nginx 以部署 Flask 应用的详细指南
  • LeetCode - 144. 二叉树的前序遍历
  • 电工基础【5】简单的电路设计接线实操
  • python直方图
  • 转战web3远程工作的英语学习的路线规划
  • 安全-JAVA开发-第一天
  • 数据可视化有哪些步骤?2025高效落地指南