swoole4.0之打造自己的web开发框架(6)

2018年12月30日 268点热度 0人点赞 0条评论

上一篇: swoole4.0之打造自己的web开发框架(5), 我们引入了composer支持,可以让我们的框架复用无数的优秀的库,在示例中,我们通过引用了fastrouter改造了router,让router的能力大大增强并且灵活, 本篇继续完善框架之旅


一、PSR7规范


HTTP 消息是 Web 技术发展的基础。浏览器或 HTTP 客户端如 curl 生成发送 HTTP 请求消息到 Web 服务器,Web 服务器响应 HTTP 请求。服务端的代码接受 HTTP 请求消息后返回 HTTP 响应消息。

通常 HTTP 消息对于终端用户来说是不可见的,但是作为 Web 开发者,我们需要知道 HTTP 机制,如何发起、构建、取用还有操纵 HTTP 消息,知道这些原理,以助我们更好的完成开发任务,无论这个任务是发起一个 HTTP 请求,或者处理传入的请求


PSR7 正是 HTTP消息的规范,规范了request, response的读取和各种行为,是非常有必要和有意义的


swoole在http提供了 swoole_http_request和swoole_http_response,所以我们要在这两个对象的基础上封装,让其符合PSR7


首先,我们在composer里引入

"easyswoole/http": "^1.0",

这是一个现成封装好符合PSR7的swoole request/response的库

然后我们把Family/Coroutine/Context.php 改造:

<?php
//file Family/Coroutine/Context.php
namespace Family\Coroutine;


use EasySwoole\Http\Request;
use EasySwoole\Http\Response;

class Context
{
/**
    * @var Request
    */
   private $request;
/**
    * @var Response
    */
   private $response;

/**
    * @var array 一个array,可以存取想要的任何东西
    */
   private $map = [];

public function __construct(\swoole_http_request $request, \swoole_http_response $response)
{
$this->request = new Request($request);
$this->response = new Response($response);
}

/**
    * @return Request
    */
   public function getRequest()
{
return $this->request;
}

/**
    * @return Response
    */
   public function getResponse()
{
return $this->response;
}

/**
    * @param $key
    * @param $val
    */
   public function set($key, $val)
{
$this->map[$key] = $val;
}

/**
    * @param $key
    * @return mixed|null
    */
   public function get($key)
{
if (isset($this->map[$key])) {
return $this->map[$key];
}

return null;
}
}

这样,我们就符合了PSR7规范了,在Router层,我们获取path的方式就改成:

$path = $request->getUri()->getPath();

在Controller层,我们获取参数的方式就变成了:

/**
* @return false|string
* @throws \Exception
* @desc 返回一个用户信息
*/
public function user()
{
//PSR7获取参数的规范
   $uid = $this->request->getQueryParam('uid');
if (empty($uid)) {
throw new \Exception("uid 不能为空 ");
}
$result = UserService::getInstance()->getUserInfoByUId($uid);
return json_encode($result);

}

二、模板引擎

现代做web开发,虽然前后分离应用比较广泛,但页面输出也还是避免不了的,特别对于小团队,PHPer前后包揽,还是用模板引擎开发效率最高

同样受益于composer,我们直接引用了一个非常优秀的模板引擎:

"twig/twig": "~1.0",

关于twig的使用,这里不展开,不太熟悉的可以放一下官方文档(还是很简单的,我也是花了大概半小时了解了一下)

我们先设置模板引擎的一些配置:

<?php
use Family\Family;

return [
'template' => [
//模板页面的存放目录
       'path' => Family::$applicationPath . DS . 'template' . DS . 'default', //模版目录, 空则默认 template/default
       //模板缓存页面的存放目录
       'cache' => Family::$applicationPath . DS . 'template' . DS . 'default_cache', //缓存目录, 空则默认 template/default_cache
   ]
];

然后我们定义一个Helper页面,做引擎的一些初始化工作:

<?php
//file framework/Helper/Template.php
namespace Family\Helper;


use Family\Core\Config;
use Family\Core\Singleton;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class Template
{
use Singleton;

public $template;

public function __construct()
{
$templateConfig = Config::get('template');
$loader = new FilesystemLoader($templateConfig['path']);
$this->template = new Environment($loader, array(
'cache' => $templateConfig['cache'],
));
}
}

然后我们在Controller基类里引用模板引擎

<?php
//file framework/Family/MVC/Controller.php
namespace Family\MVC;


use Family\Core\Config;
use Family\Helper\Template;
use Family\Pool\Context;

class Controller
{
protected $request;
/**
    * @var \Twig\Environment
    */
   protected $template;

const _CONTROLLER_KEY_ = '__CTR__';
const _METHOD_KEY_ = '__METHOD__';

public function __construct()
{
//通过context拿到$request, 再也不用担收数据错乱了
       $context = Context::getContext();
$this->request = $context->getRequest();
$this->template = Template::getInstance()->template;
}

}

 这样,我们就有了模板引擎的能力了,让我们在controller试一下吧:

class Index extends Controller
{
public function index()
{
return $this->template->render('index.twig', [
'name' => 'tong'
       ]);
}

我们看一下模板内容
(path: application/template/default/index.twig):

<!DOCTYPE html>
<html>
<head>
   <title>Index</title>
</head>
<body>
<h1>{{ name }}</h1>
</body>
</html>

访问 http://127.0.0.1:9501/:

图片

输出正确结果

本篇的内容再一次证明了composer的强大的伟大,很容易引用现有非常成熟的库丰富我们的框架


下一篇, 也是2019开年第一篇,我们将通过修复之前文章出现的mysql一个bug,来详细介绍如何在swoole中正确使用单例,也有助于大家理解swoole里的一些基础概念和进程、请求、协程的生存周期介绍


查看原文,了解PSR7规范

github地址: https://github.com/shenzhe/family

 ----------伟大的分割线-----------

PHP饭米粒(phpfamily) 由一群靠谱的人建立,愿为PHPer带来一些值得细细品味的精神食粮!

饭米粒只发原创或授权发表的文章,不转载网上的文章

所发的文章,均可找到原作者进行沟通。

也希望各位多多打赏(算作稿费给文章作者),更希望大家多多投搞。

投稿请联系:

[email protected]

本文由 半桶水 授权 饭米粒 发布,转载请注明本来源信息和以下的二维码(长按可识别二维码关注)

图片

35880swoole4.0之打造自己的web开发框架(6)

这个人很懒,什么都没留下

文章评论