当前位置: 首页 > 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>

相关文章:

  • Spring Bean 为何“难产”?攻克构造器注入的依赖与歧义
  • Q:知识库-文档的搜索框逻辑是怎样的?
  • 【论文解读】ReAct:从思考脱离行动, 到行动反馈思考
  • CAMEL-AI开源自动化任务执行助手OWL一键整合包下载
  • 普中STM32F103ZET6开发攻略(三)
  • 什么是 /proc/buddyinfo
  • redis缓存常见问题
  • 12.7 LangChain实战:1.2秒响应!用LCEL构建高效RAG系统,准确率提升41%
  • 力扣 88.合并两个有序数组
  • vscode配置lua
  • PowerShell脚本编程基础指南
  • 《认知觉醒》第二章——驯服你的“脑内大象”:理智、本能与情绪的共生之道
  • 【Harmony OS】数据存储
  • Modbus转Ethernet IP网关助力罗克韦尔PLC数据交互
  • 项目目标和期望未被清晰传达,如何改进?
  • 【计算机网络】第七章 运输层
  • 动态规划-数位DP
  • 【学习笔记】深度学习-过拟合解决方案
  • 基于Halcon深度学习之分类
  • 【bpmn.js 使用总结】最简单实现Palette
  • 驻马店企业做网站/更厉害的病毒2024
  • 网站设计一般包括什么/百度联盟项目看广告挣钱
  • 做网站怎么样才能排在首页/网络营销属于什么专业类型
  • 电脑记事本做网站/关键词排名seo优化
  • 郑州做网站推广多少钱/长沙网站seo优化公司
  • 项目经理资格证/西安网络优化培训机构公司