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

发布于:2025-06-04 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、安装依赖插件

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

<?php


namespace 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>

网站公告

今日签到

点亮在社区的每一天
去签到