學習路之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
繁體地址,請注明出處:http://hk.pswp.cn/news/908081.shtml
英文地址,請注明出處:http://en.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…