add global_function and ZMRequest class

This commit is contained in:
whale 2020-03-19 17:43:27 +08:00
parent 9417c3f323
commit 4187bab913
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,7 @@
<?php
//这里写你的全局函数
function phptest(){
echo "Nothing.\n";
}

View File

@ -144,6 +144,10 @@ class WorkerStartEvent implements SwooleEvent
//加载Custom目录下的自定义的内部类
ConnectionManager::registerCustomClass();
//加载自定义的全局函数
if(file_exists(WORKING_DIR."/src/Custom/global_function.php"))
require_once WORKING_DIR."/src/Custom/global_function.php";
}
private function setAutosaveTimer($globals) {

View File

@ -0,0 +1,75 @@
<?php
namespace ZM\Utils;
use Swlib\Saber;
use Swoole\Coroutine\Http\Client;
class ZMRequest
{
/**
* 使用Swoole协程客户端发起HTTP GET请求
* @version 1.1
* 返回请求后的body
* 如果请求失败或返回状态不是200则返回 false
* @param $url
* @param array $headers
* @param array $set
* @param bool $return_body
* @return bool|string|Client
*/
public static function get($url, $headers = [], $set = [], $return_body = true) {
$parse = parse_url($url);
$cli = new Client($parse["host"], ($parse["scheme"] == "https" ? 443 : (isset($parse["port"]) ? $parse["port"] : 80)), ($parse["scheme"] == "https" ? true : false));
$cli->setHeaders($headers);
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
$cli->get($parse["path"] . (isset($parse["query"]) ? "?" . $parse["query"] : ""));
if ($return_body) {
if ($cli->errCode != 0 || $cli->statusCode != 200) return false;
$a = $cli->body;
$cli->close();
return $a;
} else {
$cli->close();
return $cli;
}
}
/**
* 使用Swoole协程客户端发起HTTP POST请求
* 返回请求后的body
* 如果请求失败或返回状态不是200则返回 false
* @param $url
* @param array $header
* @param $data
* @param array $set
* @param bool $return_body
* @return bool|string|Client
*/
public static function post($url, array $header, $data, $set = [], $return_body = true) {
$parse = parse_url($url);
$cli = new Client($parse["host"], ($parse["scheme"] == "https" ? 443 : (isset($parse["port"]) ? $parse["port"] : 80)), ($parse["scheme"] == "https" ? true : false));
$cli->set($set == [] ? ['timeout' => 15.0] : $set);
$cli->setHeaders($header);
$cli->post($parse["path"] . (isset($parse["query"]) ? ("?" . $parse["query"]) : ""), $data);
if ($return_body) {
if ($cli->errCode != 0 || $cli->statusCode != 200) return false;
$a = $cli->body;
$cli->close();
return $a;
} else {
$cli->close();
return $cli;
}
}
/**
* @param $option
* @return Saber
*/
public static function session($option) {
return Saber::session($option);
}
}