学习路之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.pswp.cn/news/908081.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

设计模式——享元设计模式(结构型)

摘要 享元设计模式是一种结构型设计模式&#xff0c;旨在通过共享对象减少内存占用和提升性能。其核心思想是将对象状态分为内部状态&#xff08;可共享&#xff09;和外部状态&#xff08;不可共享&#xff09;&#xff0c;并通过享元工厂管理共享对象池。享元模式包含抽象享…

互联网大厂Java求职面试:云原生微服务架构设计与AI大模型集成实战

互联网大厂Java求职面试&#xff1a;云原生微服务架构设计与AI大模型集成实战 面试场景设定 人物设定&#xff1a; 李明&#xff08;技术总监&#xff09;&#xff1a;拥有15年分布式系统架构经验&#xff0c;主导过多个亿级用户系统的重构&#xff0c;对云原生和AI融合有深…

nginx+tomcat动静分离、负载均衡

一、理论 nginx用于处理静态页面以及做调度器&#xff0c;tomcat用于处理动态页面 lvs&#xff08;四层&#xff09; 轮询&#xff08;rr&#xff09; 加权轮询&#xff08;wrr&#xff09; 最小连接&#xff08;lc&#xff09; 加权最小连接&#xff08;wlc&#xff09; ngi…

什么是AI芯片?

首先&#xff0c;我们要了解一下&#xff1a;什么是芯片&#xff1f;芯片的本质就是在半导体衬底上制作能实现一系列特定功能的集成电路。 其次&#xff0c;来看一下AI的概念。AI是研究如何使计算机能够模拟和执行人类智能任务的科学和技术领域&#xff0c;致力于开发能够感知…

PostgreSQL数据库配置SSL操作说明书

背景&#xff1a; 因为postgresql或者mysql目前通过docker安装&#xff0c;只需要输入主机IP、用户名、密码即可访问成功&#xff0c;这样其实是不安全的&#xff0c;可能会通过一些手段获取到用户名密码导致数据被窃取。而ES、kafka等也是通过用户名/密码方式连接&#xff0c;…

k8s更新证书

[rootk8s-master01 ~]# sudo kubeadm certs renew all [renew] Reading configuration from the cluster… [renew] FYI: You can look at this config file with ‘kubectl -n kube-system get cm kubeadm-config -o yaml’ certificate embedded in the kubeconfig file for…

正点原子lwIP协议的学习笔记

正点原子lwIP协议的学习笔记 正点原子lwIP学习笔记——lwIP入门 正点原子lwIP学习笔记——MAC简介 正点原子lwIP学习笔记——PHY芯片简介 正点原子lwIP学习笔记——以太网DMA描述符 正点原子lwIP学习笔记——裸机移植lwIP 正点原子lwIP学习笔记——裸机lwIP启动流程 正点…

MongoTemplate常用api学习

本文只介绍常用的api&#xff0c;尽量以最简单的形式学会mongoTemplate基础api的使用 一、新增 主要包含三个api&#xff1a;insert&#xff08;一个或遍历插多个&#xff09;、insertAll&#xff08;批量多个&#xff09;、save&#xff08;插入或更新&#xff09; //这里简…

006网上订餐系统技术解析:打造高效便捷的餐饮服务平台

网上订餐系统技术解析&#xff1a;打造高效便捷的餐饮服务平台 在数字化生活方式普及的当下&#xff0c;网上订餐系统成为连接餐饮商家与消费者的重要桥梁。该系统以菜品分类、订单管理等模块为核心&#xff0c;通过前台展示与后台录入的分工协作&#xff0c;为管理员和会员提…

网络攻防技术五:网络扫描技术

文章目录 一、网络扫描的基础概念二、主机发现三、端口扫描1、端口号2、端口扫描技术3、端口扫描隐秘策略 四、操作系统识别五、漏洞扫描六、简答题1. 主机扫描的目的是什么&#xff1f;请简述主机扫描方法。2. 端口扫描的目的是什么&#xff1f;请简述端口扫描方法及扫描策略。…

生成JavaDoc文档

生成 JavaDoc 文档 1、快速生成 文档 注解 2、常见的文档注解 3、脚本生成 doc 文档 4、IDEA工具栏生成 doc 文档 第一章 快速入门 第01节 使用插件 在插件工具当中&#xff0c;找到插件 javaDoc 使用方式&#xff0c;在代码区域&#xff0c;直接点击右键。选择 第02节 常用注…

大数据-276 Spark MLib - 基础介绍 机器学习算法 Bagging和Boosting区别 GBDT梯度提升树

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 大模型篇章已经开始&#xff01; 目前已经更新到了第 22 篇&#xff1a;大语言模型 22 - MCP 自动操作 FigmaCursor 自动设计原型 Java篇开…

【HarmonyOS 5】如何优化 Harmony-Cordova 应用的性能?

以下是针对 ‌Harmony-Cordova 应用性能优化‌的完整方案&#xff0c;结合鸿蒙原生特性和Cordova框架优化策略&#xff1a; ‌⚡一、渲染性能优化‌ ‌减少布局嵌套层级‌ 使用扁平化布局&#xff08;如 Grid、GridRow&#xff09;替代多层 Column/Row 嵌套&#xff0c;避免冗…

数据库管理-第332期 大数据已死,那什么当立?(20250602)

数据库管理332期 2025-06-02 数据库管理-第332期 大数据已死&#xff0c;那什么当立&#xff1f;&#xff08;20250602&#xff09;1 概念还是技术2 必然的大数据量3 离线到实时4 未来总结 数据库管理-第332期 大数据已死&#xff0c;那什么当立&#xff1f;&#xff08;202506…

相机--RGBD相机

教程 分类原理和标定 原理 视频总结 双目相机和RGBD相机原理 作用 RGBD相机RGB相机深度&#xff1b; RGB-D相机同时获取两种核心数据&#xff1a;RGB彩色图像和深度图像&#xff08;Depth Image&#xff09;。 1. RGB彩色图像 数据格式&#xff1a; 标准三通道矩阵&#…

神经符号集成-三篇综述

讲解三篇神经符号集成的综述&#xff0c;这些综述没有针对推荐系统的&#xff0c;所以大致过一下&#xff0c;下一篇帖子会介绍针对KG的两篇综述。综述1关注的是系统集成和数据流的宏观模式“是什么”&#xff1b;综述3关注的是与人类理解直接相关的中间过程和决策逻辑的透明度…

window/linux ollama部署模型

模型部署 模型下载表: deepseek-r1 win安装ollama 注意去官网下载ollama,这个win和linux差别不大,win下载exe linux安装ollama 采用docker方式进行安装: OLLAMA_HOST=0.0.0.0:11434 \ docker run -d \--gpus all \-p 11434:11434 \--name ollama \-v ollama:/root/.ol…

计算A图片所有颜色占B图片红色区域的百分比

import cv2 import numpy as npdef calculate_overlap_percentage(a_image_path, b_image_path):# 读取A组和B组图像a_image cv2.imread(a_image_path)b_image cv2.imread(b_image_path)# 将图像从BGR转为HSV色彩空间&#xff0c;便于颜色筛选a_hsv cv2.cvtColor(a_image, c…

每日算法 -【Swift 算法】盛最多水的容器

盛最多水的容器&#xff1a;Swift 解法与思路分析 &#x1f4cc; 问题描述 给定一个长度为 n 的整数数组 height&#xff0c;每个元素表示在横坐标 i 处的一条垂直线段的高度。任意两条线段和 x 轴构成一个容器&#xff0c;该容器可以装水&#xff0c;水量的大小由较短的那条…

云原生安全基础:Linux 文件权限管理详解

&#x1f525;「炎码工坊」技术弹药已装填&#xff01; 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 在云原生环境中&#xff0c;Linux 文件权限管理是保障系统安全的核心技能之一。无论是容器化应用、微服务架构还是基础设施即代码&#xff08;IaC&#xf…