EasyWechat是目前PHP中最好用的微信开发composer组件了,在php-fpm模式下使用是没有问题的,但是在swoole框架(例如:hyperf,easyswoole等)的项目中使用就会存在一些问题。
问题
主要是Swoole是框架都是使用每个请求都是协程处理的,所以在使用Request对象的使用就会出错。例如Hyperf就有重写的过的Request对象,而EasyWechat内的Request对象并不是重写的,所以就需要对EasyWechat内的Request对象进行重写。
重写Request对象
本次以Hyperf框架为例,在EasyWechat的app初始化之后,直接对对象的request属性进行重写。
$this->app = Factory::officialAccount($config);
//用于swoole的request原因,所以在这里需要重写
$this->app['request'] = new WechatRequest();
class WechatRequest
{
/**
* @Inject()
*/
protected RequestInterface $request;
public function __call($name, $arguments)
{
return $this->request->$name(...$arguments);
}
function get($key, $default = '')
{
return $this->request->input($key, $default);
}
function getContentType()
{
return $this->request->header('content-type', '');
}
function getContent()
{
return $this->request->getBody()
->getContents();
}
}
这里需要注意的是,Hyperf 的 RequestInterface 中没有get方法,所以这里需要重新定义get方法。