在EasySwoole中实现Tp框架中think-template模板引擎的使用
1、先安装EasySwoole模板引擎驱动
composer require easyswoole/template
2、安装 topthink/think-template
composer require topthink/think-template
3、 实现渲染引擎
<?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;
}
}
4、在http服务中心注册,EasySwooleEvent下的 mainServerCreate
<?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()]));
}
}