安装EasySwoole模板引擎驱动 composer require easyswoole/template
(EasySwoole引入模板渲染驱动的形式,把需要渲染的数据,通过协程客户端投递到自定义的同步进程中进行渲染并返回结果。为何要如此处理,原因在于,市面上的一些模板引擎在Swoole协程下存在变量安全问题)
安装ThinkPHP框架使用的模板引擎 composer require topthink/think-template
实现渲染引擎,代码如下
<?php
namespace App;
use EasySwoole\Template\RenderInterface;
class Template implements RenderInterface
{
protected $template;
function __construct()
{
$config = [
'view_path' => EASYSWOOLE_ROOT.'/App/Views/',
'cache_path' => EASYSWOOLE_ROOT.'/Temp/runtime/',
];
$this->template = new \think\Template($config);
}
public function render(string $template, array $data = [], array $options = []): ?string
{
// TODO: Implement render() method.
ob_start();
$this->template->assign($data);
$this->template->fetch($template);
$content = ob_get_contents() ;
return $content;
}
public function afterRender(?string $result, string $template, array $data = [], array $options = [])
{
// TODO: Implement afterRender() method.
}
public function onException(\Throwable $throwable): string
{
// TODO: Implement onException() method.
$msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
trigger_error($msg);
return $msg;
}
}
<?php
/**
* Created by PhpStorm.
* User: yf
* Date: 2018/5/28
* Time: 下午6:33
*/
namespace EasySwoole\EasySwoole;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Template\Render;
use App\Template;
class EasySwooleEvent implements Event
{
public static function initialize()
{
// TODO: Implement initialize() method.
date_default_timezone_set('Asia/Shanghai');
}
public static function mainServerCreate(EventRegister $register)
{
// TODO: Implement mainServerCreate() method.
//在全局的主服务中创建事件中,实例化该Render,并注入你的驱动配置
Render::getInstance()->getConfig()->setRender(new Template());
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.
}
}
5.调用模板并输出
<?php
namespace App\HttpController\Admin;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Template\Render;
class Index extends Controller
{
public function index()
{
$this->response()->write(Render::getInstance()->render('admin/index',['row'=> time()]));
}
public function console()
{
$this->response()->write(Render::getInstance()->render('admin/console'));
}
}
本文为北溟有鱼QAQ原创文章,转载无需和我联系,但请注明来自北溟有鱼QAQ https://www.amdzz.cn
最新评论