easyswoole框架使用模板直接使用模板引擎,是会有问题的,所以增加了渲染驱动
渲染驱动
EasySwoole引入模板渲染驱动的形式,把需要渲染的数据,通过协程客户端投递到自定义的同步进程中进行渲染并返回结果。为何要如此处理,原因在于,市面上的一些模板引擎在Swoole协程下存在变量安全问题。例如以下流程:
- request A reached, static A assign requestA-data
- compiled template
- write compiled template (yiled current coroutine)
- request B reached,static A assign requestB-data
- render static A data into complied template file
以上流程我们可以发现,A请求的数据,被B给污染了。为了解决该问题,EasySwoole引入模板渲染驱动模式。
安装
composer require easyswoole/template
实现渲染引擎
use EasySwoole\\Template\\Config; use EasySwoole\\Template\\Render; use EasySwoole\\Template\\RenderInterface; class R implements RenderInterface{ public function render(string $template, array $data = \[\], array $options = \[\]):?string { return 'asas'; } public function afterRender(?string $result, string $template, array $data = \[\], array $options = \[\]) { // TODO: Implement afterRender() method. } public function onException(Throwable $throwable):string { return $throwable->getMessage(); } }
在http中调用:
//在全局的主服务中创建事件中,实例化该Render,并注入你的驱动配置 Render::getInstance()->getConfig()>setRender(new R()); $http = new swoole\_http\_server("0.0.0.0", 9501); $http->on("request", function ($request, $response)use($render) { //调用渲染器,此时会通过携程客户端,把数据发往自定义的同步进程中处理,并得到渲染结果 $response->end(Render::getInstance()->render('a.html')); }); $render->attachServer($http);$http->start();
Smarty 渲染
引入:
composer require smarty/smarty
实现渲染引擎
实现渲染引擎 use EasySwoole\\Template\\RenderInterface;use EasySwoole\\Template\\RenderInterface; class Smarty implements RenderInterface{ private $smarty; function __construct() { $temp = sys\_get\_temp_dir(); $this->smarty = new \\Smarty(); $this->smarty->setTemplateDir(\_\_DIR\_\_.'/'); $this->smarty->setCacheDir("{$temp}/smarty/cache/"); $this->smarty->setCompileDir("{$temp}/smarty/compile/"); } public function render(string $template, array $data = \[\], array $options = \[\]): ?string { foreach ($data as $key => $item){ $this->smarty->assign($key,$item); } return $this->smarty->fetch($template,$cache\_id = null, $compile\_id = null, $parent = null, $display = false, $merge\_tpl\_vars = true, $no\_output\_filter = false); } public function afterRender(?string $result, string $template, array $data = \[\], array $options = \[\]) { } public function onException(\\Throwable $throwable): string { $msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}"; trigger_error($msg); return $msg; } }
在http中调用smarty:
//在全局的主服务中创建事件中,实例化该Render,并注入你的驱动配置 Render::getInstance()->getConfig()>setRender(new Smarty()); Render::getInstance()->getConfig()->setTempDir(EASYSWOOLE\_TEMP\_DIR); Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer()); //在控制器action中实现响应 Render::getInstance()->render('a.html');
本文转自 www.easyswoole.com 官方文档