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

article/2025/6/9 17:54:26

学习路之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.hkcw.cn/article/EEwmNXrSaK.shtml

相关文章

【C++高并发内存池篇】性能卷王养成记:C++ 定长内存池,让内存分配快到飞起!

&#x1f4dd;本篇摘要 在本篇将介绍C定长内存池的概念及实现问题&#xff0c;引入内存池技术&#xff0c;通过实现一个简单的定长内存池部分&#xff0c;体会奥妙所在&#xff0c;进而为之后实现整体的内存池做铺垫&#xff01; &#x1f3e0;欢迎拜访&#x1f3e0;&#xff…

前端验证下跨域问题(npm验证)

文章目录 一、背景二、效果展示三、代码展示3.1&#xff09;index.html3.2&#xff09;package.json3.3&#xff09; service.js3.4&#xff09;service2.js 四、使用说明4.1&#xff09;安装依赖4.2&#xff09;启动服务器4.3&#xff09;访问前端页面 五、跨域解决方案说明六…

nginx+Tomcat负载均衡群集

目录 一. LVS&#xff0c;HAProxy&#xff0c;Nginx的区别 1. 核心区别 2. 负载均衡算法对比 2. 1 LVS 负载均衡算法 2.2 HAProxy 负载均衡算法 2.3 Nginx 负载均衡算法 2.4 总结 二. 案例分析 1. 案例概述 (1) Tomcat 简介 (2)应用场景 2. 案例环境 3. 案例实施 …

WSL安装及使用 (适用于 Linux 的 Windows 子系统)

WSL简介 WSL&#xff1a;适用于 Linux 的 Windows 子系统&#xff0c;有1和2两个版本&#xff0c;1是windows重新实现了linux接口&#xff0c;2是原生linux内核。目前 WSL2 为默认模式&#xff0c;兼容性和性能更好。 wsl中文官网 安装 确保以下功能开启&#xff1a; 控制面…

JavaSec | SpringAOP 链学习分析

目录: 链子分析 反向分析 正向分析 poc 构造 总结 链子分析 反向分析 依赖于 Spring-AOP 和 aspectjweaver 两个包&#xff0c;在我们 springboot 中的 spring-boot-starter-aop 自带包含这俩类&#xff0c;所以也可以说是 spring boot 的原生反序化链了&#xff0c;调用…

PV操作的C++代码示例讲解

文章目录 一、PV操作基本概念&#xff08;一&#xff09;信号量&#xff08;二&#xff09;P操作&#xff08;三&#xff09;V操作 二、PV操作的意义三、C中实现PV操作的方法&#xff08;一&#xff09;使用信号量实现PV操作代码解释&#xff1a; &#xff08;二&#xff09;使…

医疗内窥镜影像工作站技术方案(续)——EFISH-SCB-RK3588国产化替代技术深化解析

一、异构计算架构的医疗场景适配 ‌多核任务调度优化‌ ‌A76/A55协同计算‌&#xff1a;4Cortex-A762.4GHz负责AI推理&#xff08;如息肉识别算法&#xff09;&#xff0c;4Cortex-A551.8GHz处理DICOM影像传输协议&#xff0c;多任务负载效率比赛扬N系列提升80%‌NPU加速矩阵…

HCIP-Datacom Core Technology V1.0_3 OSPF基础

动态路由协议简介 静态路由相比较动态路由有什么优点呢。 静态路由协议&#xff0c;当网络发生故障或者网络拓扑发生变更&#xff0c;它需要管理员手工配置去干预静态路由配置&#xff0c;但是动态路由协议&#xff0c;它能够及时自己感应网络拓扑变化&#xff0c;不路由选择…

敏捷转型:破局之道

在数字化浪潮与市场不确定性加剧的背景下&#xff0c;传统组织向敏捷组织转型已成为企业生存与发展的核心命题。这种转型并非简单的工具迭代或流程优化&#xff0c;而是涉及治理结构、文化基因与人才机制的深度重构。理解两种组织形态的本质差异&#xff0c;明确转型的适用场景…

WordPress 6.5版本带来的新功能

WordPress 6.5正式上线了&#xff01;WordPress团队再一次为我们带来了许多新的改进。在全球开发者的共同努力下&#xff0c;WordPress推出了许多新的功能&#xff0c;本文将对其进行详细总结。 Hostease的虚拟主机现已支持一键安装最新版本的WordPress。对于想要体验WordPres…

软硬解锁通用Switch大气层1.9.0系统+20.0.1固件升级 图文教程 附大气层大气层固件升级整合包下载

软硬解锁通用Switch大气层1.9.0系统20.0.1固件升级 图文教程 附大气层大气层固件升级整合包下载 大气层&#xff08;Atmosphere&#xff09;是为任天堂 Switch 主机开发的免费开源自定义固件&#xff08;CFW&#xff09;&#xff0c;由开发者 SciresM 领导的团队维护。它允许用…

Redisson学习专栏(五):源码阅读及Redisson的Netty通信层设计

文章目录 前言一、分布式锁核心实现&#xff1a;RedissonLock源码深度解析1.1 加锁机制&#xff1a;原子性与重入性实现1.2 看门狗机制&#xff1a;锁自动续期设计1.3 解锁机制&#xff1a;安全释放与通知1.4 锁竞争处理&#xff1a;等待队列与公平性1.5 容错机制&#xff1a;异…

字节新出的MCP应用DeepSearch,有点意思。

大家好&#xff0c;我是苍何。 悄悄告诉你个事&#xff0c;昨天我去杭州参加字节火山方舟举办的开发者见面会了&#xff0c;你别说&#xff0c;还真有点刘姥姥进大观园的感觉&#x1f436; 现场真实体验完这次新发布的产品和模型&#xff0c;激动的忍不住想给大家做一波分享。…

光耦电路学习,光耦输入并联电阻、并联电容,光耦输出滤波电路

一般的光耦电路&#xff0c;只需要输入限流电阻&#xff0c;输出上拉电阻即可。 实际使用时&#xff0c;比如工控等一些干扰大、存在浪涌电压等的场合&#xff0c;根据实际可以添加一些抗干扰电路、滤波电路&#xff0c;增加电路抗干扰能力。 比如&#xff1a; 1、给光耦输入两…

JVM知识

目录 运行时数据区域 程序计数器 Java虚拟机栈 局部变量表 操作数栈 动态链接 本地方法栈 Java堆 方法区 运行时常量池 字符串常量池 直接内存 Java对象的创建过程 对象的内存布局 对象的访问 常见的 GC 类型 ​​Minor GC&#xff08;Young GC&#xff09;​ …

Spring AI介绍及大模型对接

目录 1. Spring AI介绍 2. Spring AI常用组件 2.1. Chat Client API 2.2. Models 2.3. Vector Databases 2.4. RAG 2.5. MCP 3. 大模型对接举例 3.1. 获取deepseek的API keys 3.2. idea创建工程 3.3. 配置application.yml 3.4. 编写Controller测试类 3.5. 验证Con…

C++算法训练营 Day6 哈希表(1)

1.有效的字母异位词 LeetCode&#xff1a;242.有效的字母异位词 给定两个字符串s和t &#xff0c;编写一个函数来判断t是否是s的字母异位词。 示例 1: 输入: s “anagram”, t “nagaram” 输出: true 示例 2: 输入: s “rat”, t “car” 输出: false 解题思路&#xff…

LeetCode hot100-11

题目描述 题目链接&#xff1a;滑动窗口最大值 给你一个整数数组 nums&#xff0c;有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回 滑动窗口中的最大值 。 示例 1&#xff1a; 输入…

js web api阶段

一.变量声明 1.JS中的const const在js修饰数组和对象&#xff0c;本质类似与c的引用数据类型&#xff0c;所以类似于 int* const ref 修饰的是地址&#xff0c;值是可以改变的 然后下面这种情况是禁止的 左边这种都有括号&#xff0c;说明是建立了一个块新地址去存放&#xf…

【计算机网络】数据链路层——ARP协议

&#x1f525;个人主页&#x1f525;&#xff1a;孤寂大仙V &#x1f308;收录专栏&#x1f308;&#xff1a;计算机网络 &#x1f339;往期回顾&#x1f339;&#xff1a;【计算机网络】网络层IP协议与子网划分详解&#xff1a;从主机通信到网络设计的底层逻辑 &#x1f516;流…