From 8bc3b0ca27a2d4b228580d934cbb123655efbb5a Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 23 Mar 2017 15:03:14 +0800 Subject: [PATCH 01/66] Support Thinkphp5 Support Thinkphp5 --- Curl.php | 602 ++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 142 ++++++++++++ composer.json | 21 ++ 3 files changed, 765 insertions(+) create mode 100644 Curl.php create mode 100644 README.md create mode 100644 composer.json diff --git a/Curl.php b/Curl.php new file mode 100644 index 0000000..5c91f57 --- /dev/null +++ b/Curl.php @@ -0,0 +1,602 @@ + + * @copyright 2013-2017 Nils Gajsek + * @license http://opensource.org/licenses/MIT MIT Public + * @version 1.1.1 + * + */ + +namespace lobtao\thinkphp5\curl; + +/** + * cURL class + */ +class Curl +{ + // ################################################ class vars // ################################################ + + /** + * @var string + * Holds response data right after sending a request. + */ + public $response = null; + /** + * @var null|integer + * Error code holder: https://curl.haxx.se/libcurl/c/libcurl-errors.html + */ + public $errorCode = null; + + /** + * @var null|string + * Error text holder: http://php.net/manual/en/function.curl-strerror.php + */ + public $errorText = null; + + /** + * @var integer HTTP-Status Code + * This value will hold HTTP-Status Code. False if request was not successful. + */ + public $responseCode = null; + + /** + * @var string|null HTTP Response Charset + * (taken from Content-type header) + */ + public $responseCharset = null; + + /** + * @var int HTTP Response Length + * (taken from Content-length header, or strlen() of downloaded content) + */ + public $responseLength = -1; + + /** + * @var string|null HTTP Response Content Type + * (taken from Content-type header) + */ + public $responseType = null; + + /** + * @var array|null HTTP Response headers + * Lists response header in an array if CURLOPT_HEADER is set to true. + */ + public $responseHeaders = null; + + /** + * @var array HTTP-Status Code + * Custom options holder + */ + protected $_options = []; + + /** + * @var array + * Hold array of get params to send with the request + */ + protected $_getParams = []; + + /** + * @var array + * Hold array of post params to send with the request + */ + protected $_postParams = []; + + /** + * @var resource|null + * Holds cURL-Handler + */ + protected $_curl = null; + + /** + * @var string + * hold base URL + */ + protected $_baseUrl = ''; + + /** + * @var array default curl options + * Default curl options + */ + protected $_defaultOptions = [ + CURLOPT_USERAGENT => 'thinkphp5-Curl-Agent', + CURLOPT_TIMEOUT => 30, + CURLOPT_CONNECTTIMEOUT => 30, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HEADER => true, + ]; + + + // ############################################### class methods // ############################################## + + /** + * Start performing GET-HTTP-Request + * + * @param string $url + * @param boolean $raw if response body contains JSON and should be decoded + * + * @return mixed response + */ + public function get($url, $raw = true) + { + $this->_baseUrl = $url; + return $this->_httpRequest('GET', $raw); + } + + + /** + * Start performing HEAD-HTTP-Request + * + * @param string $url + * + * @return mixed response + */ + public function head($url) + { + $this->_baseUrl = $url; + return $this->_httpRequest('HEAD'); + } + + + /** + * Start performing POST-HTTP-Request + * + * @param string $url + * @param boolean $raw if response body contains JSON and should be decoded + * + * @return mixed response + */ + public function post($url, $raw = true) + { + $this->_baseUrl = $url; + return $this->_httpRequest('POST', $raw); + } + + + /** + * Start performing PUT-HTTP-Request + * + * @param string $url + * @param boolean $raw if response body contains JSON and should be decoded + * + * @return mixed response + */ + public function put($url, $raw = true) + { + $this->_baseUrl = $url; + return $this->_httpRequest('PUT', $raw); + } + + + /** + * Start performing PATCH-HTTP-Request + * + * @param string $url + * @param boolean $raw if response body contains JSON and should be decoded + * + * @return mixed response + */ + public function patch($url, $raw = true) + { + $this->_baseUrl = $url; + return $this->_httpRequest('PATCH',$raw); + } + + + /** + * Start performing DELETE-HTTP-Request + * + * @param string $url + * @param boolean $raw if response body contains JSON and should be decoded + * + * @return mixed response + */ + public function delete($url, $raw = true) + { + $this->_baseUrl = $url; + return $this->_httpRequest('DELETE', $raw); + } + + + /** + * Set curl option + * + * @param string $key + * @param mixed $value + * + * @return $this + */ + public function setOption($key, $value) + { + //set value + if (array_key_exists($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) { + $this->_defaultOptions[$key] = $value; + } else { + $this->_options[$key] = $value; + } + + //return self + return $this; + } + + + /** + * Set get params + * + * @param array $params + * @return $this + */ + public function setGetParams($params) + { + if (is_array($params)) { + foreach ($params as $key => $value) { + $this->_getParams[$key] = $value; + } + } + + //return self + return $this; + } + + + /** + * Set get params + * + * @param array $params + * @return $this + */ + public function setPostParams($params) + { + if (is_array($params)) { + $this->setOption( + CURLOPT_POSTFIELDS, + http_build_query($params) + ); + } + + //return self + return $this; + } + + + /** + * Set get params + * + * @param string $data + * @return $this + */ + public function setRequestBody($data) + { + if (is_string($data)) { + $this->setOption( + CURLOPT_POSTFIELDS, + $data + ); + } + + //return self + return $this; + } + + + /** + * Get URL - return URL parsed with given params + * + * @return string The full URL with parsed get params + */ + public function getUrl() + { + if (Count($this->_getParams) > 0) { + return $this->_baseUrl.'?'.http_build_query($this->_getParams); + } else { + return $this->_baseUrl; + } + } + + + /** + * Set curl options + * + * @param array $options + * + * @return $this + */ + public function setOptions($options) + { + $this->_options = $options + $this->_options; + + return $this; + } + + + /** + * Set header for request + * + * @param array $headers + * + * @return $this + */ + public function setHeaders($headers) + { + if (is_array($headers)) { + + //init + $parsedHeader = []; + + //parse header into right format key:value + foreach ($headers as $header => $value) { + array_push($parsedHeader, $header.':'.$value); + } + + //set headers + $this->setOption( + CURLOPT_HTTPHEADER, + $parsedHeader + ); + } + + return $this; + } + + + /** + * Unset a single curl option + * + * @param string $key + * + * @return $this + */ + public function unsetOption($key) + { + //reset a single option if its set already + if (isset($this->_options[$key])) { + unset($this->_options[$key]); + } + + return $this; + } + + + /** + * Unset all curl option, excluding default options. + * + * @return $this + */ + public function unsetOptions() + { + //reset all options + if (isset($this->_options)) { + $this->_options = []; + } + + return $this; + } + + + /** + * Total reset of options, responses, etc. + * + * @return $this + */ + public function reset() + { + if ($this->_curl !== null) { + curl_close($this->_curl); //stop curl + } + + //reset all options + if (isset($this->_options)) { + $this->_options = []; + } + + //reset response & status params + $this->_curl = null; + $this->errorCode = null; + $this->response = null; + $this->responseCode = null; + $this->responseCharset = null; + $this->responseLength = -1; + $this->responseType = null; + $this->errorText = null; + $this->_postParams = []; + $this->_getParams = []; + + return $this; + } + + + /** + * Return a single option + * + * @param string|integer $key + * @return mixed|boolean + */ + public function getOption($key) + { + //get merged options depends on default and user options + $mergesOptions = $this->getOptions(); + + //return value or false if key is not set. + return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false; + } + + + /** + * Return merged curl options and keep keys! + * + * @return array + */ + public function getOptions() + { + return $this->_options + $this->_defaultOptions; + } + + + /** + * Get curl info according to http://php.net/manual/de/function.curl-getinfo.php + * + * @param null $opt + * @return array|mixed + */ + public function getInfo($opt = null) + { + if ($this->_curl !== null && $opt === null) { + return curl_getinfo($this->_curl); + } elseif ($this->_curl !== null && $opt !== null) { + return curl_getinfo($this->_curl, $opt); + } else { + return []; + } + } + + + /** + * Performs HTTP request + * + * @param string $method + * @param boolean $raw if response body contains JSON and should be decoded -> helper. + * + * @throws Exception if request failed + * + * @return mixed + */ + protected function _httpRequest($method, $raw = false) + { + //set request type and writer function + $this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method)); + + //check if method is head and set no body + if ($method === 'HEAD') { + $this->setOption(CURLOPT_NOBODY, true); + $this->unsetOption(CURLOPT_WRITEFUNCTION); + } + + /** + * proceed curl + */ + $curlOptions = $this->getOptions(); + $this->_curl = curl_init($this->getUrl()); + curl_setopt_array($this->_curl, $curlOptions); + $response = curl_exec($this->_curl); + + //check if curl was successful + if ($response === false) { + + //set error code + $this->errorCode = curl_errno($this->_curl); + $this->errorText = curl_strerror($this->errorCode); + + switch ($this->errorCode) { + // 7, 28 = timeout + case 7: + case 28: + $this->responseCode = 'timeout'; + return false; + break; + + default: + return false; + break; + } + } + + //extract header / body data if CURLOPT_HEADER are set to true + if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) { + $this->response = $this->_extractCurlBody($response); + $this->responseHeaders = $this->_extractCurlHeaders($response); + } else { + $this->response = $response; + } + + // Extract additional curl params + $this->_extractAdditionalCurlParameter(); + + //check responseCode and return data/status + if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') { + return true; + } else { + $this->response = $raw ? $this->response : Json::decode($this->response); + return $this->response; + } + } + + + /** + * Extract additional curl params protected class helper + */ + protected function _extractAdditionalCurlParameter () + { + + /** + * retrieve response code + */ + $this->responseCode = curl_getinfo($this->_curl, CURLINFO_HTTP_CODE); + + + /** + * try extract response type & charset. + */ + $this->responseType = curl_getinfo($this->_curl, CURLINFO_CONTENT_TYPE); + + if (!is_null($this->responseType) && count(explode(';', $this->responseType)) > 1) { + + list($this->responseType, $possibleCharset) = explode(';', $this->responseType); + + //extract charset + if (preg_match('~^charset=(.+?)$~', trim($possibleCharset), $matches) && isset($matches[1])) { + $this->responseCharset = strtolower($matches[1]); + } + } + + + /** + * try extract response length + */ + $this->responseLength = curl_getinfo($this->_curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD); + + if((int)$this->responseLength == -1) { + $this->responseLength = strlen($this->response); + } + } + + + /** + * Extract body curl data from response + * + * @param string $response + * @return string + */ + protected function _extractCurlBody ($response) + { + return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE)); + } + + + /** + * Extract header curl data from response + * + * @param string $response + * @return array + */ + protected function _extractCurlHeaders ($response) + { + //Init + $headers = []; + $headerText = substr($response, 0, strpos($response, "\r\n\r\n")); + + foreach (explode("\r\n", $headerText) as $i => $line) { + if ($i === 0) { + $headers['http_code'] = $line; + } else { + list ($key, $value) = explode(':', $line); + $headers[$key] = ltrim($value); + } + } + + return $headers; + } +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..404276a --- /dev/null +++ b/README.md @@ -0,0 +1,142 @@ +thinkphp5-curl extension +=================== +[![Latest Stable Version](https://poser.pugx.org/lobtao/thinkphp5-curl/v/stable)](https://packagist.org/packages/lobtao/thinkphp5-curl) +[![Total Downloads](https://poser.pugx.org/lobtao/thinkphp5-curl/downloads)](https://packagist.org/packages/lobtao/thinkphp5-curl) +[![License](https://poser.pugx.org/lobtao/thinkphp5-curl/license)](https://packagist.org/packages/lobtao/thinkphp5-curl) + +Easy working cURL extension for thinkphp5, including RESTful support: + + - POST + - GET + - HEAD + - PUT + - PATCH + - DELETE + +Requirements +------------ +- PHP 5.4+ +- Curl and php-curl installed + + +Installation +------------ + +The preferred way to install this extension is through [composer](http://getcomposer.org/download/). + +```bash +php composer.phar require --prefer-dist lobtao/thinkphp5-curl "*" +``` + + +Usage +----- + +Once the extension is installed, simply use it in your code. The following example shows you how to handling a simple GET Request. + +```php +use lobtao\thinkphp5\curl; +$curl = new curl\Curl(); + +//get http://example.com/ +$response = $curl->get('http://example.com/'); + +if ($curl->errorCode === null) { + echo $response; +} else { + // List of curl error codes here https://curl.haxx.se/libcurl/c/libcurl-errors.html + switch ($curl->errorCode) { + + case 6: + //host unknown example + break; + } +} +``` + +```php +// GET request with GET params +// http://example.com/?key=value&scondKey=secondValue +$curl = new curl\Curl(); +$response = $curl->setGetParams([ + 'key' => 'value', + 'secondKey' => 'secondValue' + ]) + ->get('http://example.com/'); +``` + + +```php +// POST URL form-urlencoded +$curl = new curl\Curl(); +$response = $curl->setPostParams([ + 'key' => 'value', + 'secondKey' => 'secondValue' + ]) + ->post('http://example.com/'); +``` + +```php +// POST with special headers +$curl = new curl\Curl(); +$response = $curl->setPostParams([ + 'key' => 'value', + 'secondKey' => 'secondValue' + ]) + ->setHeaders([ + 'Custom-Header' => 'user-b' + ]) + ->post('http://example.com/'); +``` + + +```php +// POST JSON with body string & special headers +$curl = new curl\Curl(); + +$params = [ + 'key' => 'value', + 'secondKey' => 'secondValue' +]; + +$response = $curl->setRequestBody(json_encode($params)) + ->setHeaders([ + 'Content-Type' => 'application/json', + 'Content-Length' => strlen(json_encode($params)) + ]) + ->post('http://example.com/'); +``` + +```php +// Avanced POST request with curl options & error handling +$curl = new curl\Curl(); + +$params = [ + 'key' => 'value', + 'secondKey' => 'secondValue' +]; + +$response = $curl->setRequestBody(json_encode($params)) + ->setOption(CURLOPT_ENCODING, 'gzip') + ->post('http://example.com/'); + +// List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes +switch ($curl->responseCode) { + + case 'timeout': + //timeout error logic here + break; + + case 200: + //success logic here + break; + + case 404: + //404 Error logic here + break; +} + +//list response headers +var_dump($curl->responseHeaders); +``` +Support Thinkphp5 \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..a33f61d --- /dev/null +++ b/composer.json @@ -0,0 +1,21 @@ +{ + "name": "lobtao/thinkphp5-curl", + "description": "Easy and nice cURL extension with RESTful support for Thinkphp5", + "type": "thinkphp5-extension", + "keywords": ["thinkphp5","extension"," curl", "RESTful"], + "license": "MIT", + "authors": [ + { + "name": "lobtao", + "email": "lobtao@qq.com" + } + ], + "require": { + "ext-curl": "*" + }, + "autoload": { + "psr-4": { + "lobtao\\thinkphp5\\curl\\": "" + } + } +} From 5fc962a968ddb1fdecb6ea8036a0dcbbe049062c Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 19 Apr 2017 14:47:11 +0800 Subject: [PATCH 02/66] add rpc --- Curl.php => src/Curl.php | 2 +- src/RpcController.php | 98 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) rename Curl.php => src/Curl.php (99%) create mode 100644 src/RpcController.php diff --git a/Curl.php b/src/Curl.php similarity index 99% rename from Curl.php rename to src/Curl.php index 5c91f57..e52e58d 100644 --- a/Curl.php +++ b/src/Curl.php @@ -12,7 +12,7 @@ * */ -namespace lobtao\thinkphp5\curl; +namespace lobtao\tp5helper; /** * cURL class diff --git a/src/RpcController.php b/src/RpcController.php new file mode 100644 index 0000000..360b068 --- /dev/null +++ b/src/RpcController.php @@ -0,0 +1,98 @@ +namespace = $namespace; + + $request = $this->request; + if ($request->isGet()) return 'API服务接口'; + + error_reporting(E_ERROR); + set_exception_handler([$this, "exception_handler"]); + + $this->func = $request->param('f'); + $this->args = $request->param('p', []); + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = json_decode($this->args, true); + } + $this->callback = $request->param('callback'); + + $result = $this->callFunc($this->func, $this->args); + return $this->ajaxReturn( + [ + 'data' => $result,//返回数据 + 'retid' => 1,//调用成功标识 + ], + $this->callback//jsonp调用时的回调函数 + ); + } + + /** + * 异常拦截回复 + * @param \Exception $exception + * @return String + */ + function exception_handler($exception) { + $errMsg = $exception->getMessage(); + $response = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); + $response->send(); + } + + /** + * 以‘-’来分割ajax传递过来的类名和方法名,调用该方法,并返回值 + * @param $func + * @param $args + * @return mixed + * @throws \Exception + */ + public function callFunc($func, $args) { + $params = explode('_', $func, 2); + if (count($params) != 2) throw new \Exception('请求参数错误'); + + $svname = ucfirst($params[0]); + $classname = $this->namespace . $svname . 'Service'; + $funcname = $params[1]; + if (!class_exists($classname)) throw new \Exception('类' . $svname . '不存在!!!'); + $object = new $classname(); + if (!method_exists($object, $funcname)) throw new \Exception($svname . '中不存在' . $funcname . '方法'); + $data = call_user_func_array([$object, $funcname], $args); + return $data; + } + + /** + * ajax返回 + * @param $result + * @param $callback + * @return \think\response\Json|\think\response\Jsonp + */ + public function ajaxReturn($result, $callback) { + return $callback ? jsonp($result) : json($result); + } + + /** + * 测试 + */ + function test() { + echo THINK_VERSION; + return $this->fetch(); + } + +} \ No newline at end of file From e64d00a91f3bc44dc634560c45fe11dd92630c13 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 19 Apr 2017 14:48:21 +0800 Subject: [PATCH 03/66] add rpc --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index a33f61d..5b1a034 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { - "name": "lobtao/thinkphp5-curl", - "description": "Easy and nice cURL extension with RESTful support for Thinkphp5", + "name": "lobtao/tp5helper", + "description": "thinkphp5 helper", "type": "thinkphp5-extension", "keywords": ["thinkphp5","extension"," curl", "RESTful"], "license": "MIT", @@ -15,7 +15,7 @@ }, "autoload": { "psr-4": { - "lobtao\\thinkphp5\\curl\\": "" + "lobtao\\tp5helper\\": "" } } } From 5d5f8f8fceba392231073470dfc6847b27039500 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 19 Apr 2017 14:54:58 +0800 Subject: [PATCH 04/66] add rpc --- README.md | 2 +- composer.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 404276a..e9596ec 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -thinkphp5-curl extension +thinkphp5-helper =================== [![Latest Stable Version](https://poser.pugx.org/lobtao/thinkphp5-curl/v/stable)](https://packagist.org/packages/lobtao/thinkphp5-curl) [![Total Downloads](https://poser.pugx.org/lobtao/thinkphp5-curl/downloads)](https://packagist.org/packages/lobtao/thinkphp5-curl) diff --git a/composer.json b/composer.json index 5b1a034..9b399b1 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,8 @@ { "name": "lobtao/tp5helper", "description": "thinkphp5 helper", - "type": "thinkphp5-extension", - "keywords": ["thinkphp5","extension"," curl", "RESTful"], + "type": "thinkphp5-helper", + "keywords": ["thinkphp5","extension"," curl", "RESTful","helper"], "license": "MIT", "authors": [ { From 72a73cfd52cb00b12ab92ed490a2816c5a3aa332 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 19 Apr 2017 15:01:46 +0800 Subject: [PATCH 05/66] add rpc --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 9b399b1..f43c2d7 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,7 @@ }, "autoload": { "psr-4": { - "lobtao\\tp5helper\\": "" + "lobtao\\tp5helper\\": "src/" } } } From 7e1b44d6db7699b272f4896d05dfc7a9072e500e Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 19 Apr 2017 15:11:23 +0800 Subject: [PATCH 06/66] add rpc --- src/RpcController.php | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 360b068..0696158 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -87,12 +87,4 @@ public function ajaxReturn($result, $callback) { return $callback ? jsonp($result) : json($result); } - /** - * 测试 - */ - function test() { - echo THINK_VERSION; - return $this->fetch(); - } - } \ No newline at end of file From f829e0eca54e43c2c48bd7501b1176a1433608e0 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 25 Apr 2017 17:44:28 +0800 Subject: [PATCH 07/66] auto send data --- src/RpcController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/RpcController.php b/src/RpcController.php index 0696158..5165ce6 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -33,13 +33,14 @@ public function handle($namespace) { $this->callback = $request->param('callback'); $result = $this->callFunc($this->func, $this->args); - return $this->ajaxReturn( + $response = $this->ajaxReturn( [ 'data' => $result,//返回数据 'retid' => 1,//调用成功标识 ], $this->callback//jsonp调用时的回调函数 ); + $response->send(); } /** From 3bcad094d2a61846a9b9244acd206d612ed295ec Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 24 May 2017 19:28:01 +0800 Subject: [PATCH 08/66] add helper functions --- composer.json | 3 +++ src/Helper.php | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/Helper.php diff --git a/composer.json b/composer.json index f43c2d7..7953e96 100644 --- a/composer.json +++ b/composer.json @@ -14,6 +14,9 @@ "ext-curl": "*" }, "autoload": { + "files": [ + "src/Helper.php" + ], "psr-4": { "lobtao\\tp5helper\\": "src/" } diff --git a/src/Helper.php b/src/Helper.php new file mode 100644 index 0000000..475f0e0 --- /dev/null +++ b/src/Helper.php @@ -0,0 +1,48 @@ +root(); + $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base; + if ('' != $root) { + $root = '/' . ltrim($root, '/'); + } + return $root; + } +} + + +if (!function_exists('V')) { + /** + * 快捷校验方法 + * @param \think\Validate $validate + * @param String $scenario + * @param Array $params + * @param bool|true $showException + * @return string + * @throws Exception + */ + function V($validate, $scenario, $params, $showException = true) { + //校验输入值 + $msg = ''; + if (!$validate->scene($scenario)->check($params)) { + $msg = $validate->getError(); + + if ($showException) throw new \Exception($msg); + } + return $msg; + } +} \ No newline at end of file From aa3b47b7d05c73cc05d45de81b7150194b901f75 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 24 May 2017 19:33:48 +0800 Subject: [PATCH 09/66] add helper functions --- src/Helper.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index 475f0e0..41c28d6 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -1,7 +1,7 @@ Date: Wed, 24 May 2017 20:19:08 +0800 Subject: [PATCH 10/66] fixed bugs --- src/RpcController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 5165ce6..2531f33 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -64,7 +64,7 @@ function exception_handler($exception) { * @return mixed * @throws \Exception */ - public function callFunc($func, $args) { + private function callFunc($func, $args) { $params = explode('_', $func, 2); if (count($params) != 2) throw new \Exception('请求参数错误'); @@ -84,7 +84,7 @@ public function callFunc($func, $args) { * @param $callback * @return \think\response\Json|\think\response\Jsonp */ - public function ajaxReturn($result, $callback) { + private function ajaxReturn($result, $callback) { return $callback ? jsonp($result) : json($result); } From 48eaf00eac7b347b89de8fcb8eb23fcdf0292407 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 15:25:10 +0800 Subject: [PATCH 11/66] =?UTF-8?q?add=20=E6=8E=88=E6=9D=83=E8=AE=BF?= =?UTF-8?q?=E9=97=AE=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/RpcController.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/RpcController.php b/src/RpcController.php index 2531f33..fc9a565 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -16,22 +16,29 @@ class RpcController extends Controller { * @return string|\think\response\Json|\think\response\Jsonp * @throws \Exception */ - public function handle($namespace) { + public function handle($namespace,$filter=null) { $this->namespace = $namespace; $request = $this->request; if ($request->isGet()) return 'API服务接口'; + //异常拦截 error_reporting(E_ERROR); set_exception_handler([$this, "exception_handler"]); $this->func = $request->param('f'); $this->args = $request->param('p', []); + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 $this->args = json_decode($this->args, true); } $this->callback = $request->param('callback'); + //过滤处理 + if($filter){ + call_user_func_array($filter, [$this->func,$this->args]); + } + $result = $this->callFunc($this->func, $this->args); $response = $this->ajaxReturn( [ From 7c4b765b037d022365c602a492c8e576d1a7eeef Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 16:55:04 +0800 Subject: [PATCH 12/66] update readme --- README.md | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e9596ec..d25cbe6 100644 --- a/README.md +++ b/README.md @@ -139,4 +139,69 @@ switch ($curl->responseCode) { //list response headers var_dump($curl->responseHeaders); ``` -Support Thinkphp5 \ No newline at end of file + +RpcController.php RPC远程调用示例 +----- +ServiceController.php 服务提供接口 + +```php +namespace app\index\controller; + +use lobtao\tp5helper\RpcController; +use think\Session; + +class ServiceController extends RpcController { + + function index() { + $this->handle('app\\service\\', function ($func, $params) { + if (in_array(strtolower($func), ['user_login', 'user_logout'])) //登录方法不判断 + return; + + if(!Session::get('user')){ + throw new \Exception('尚未登录,不能访问'); + } + }); + } +} +``` + +UserService.php 服务类 + +```php +namespace app\service; + + +use think\Session; + +class UserService { + function login(){ + Session::set('user', ['name'=>'远思']); + } + + function logout(){ + Session::delete('user'); + Session::destroy(); + } + + function test(){ + return '恭喜,你可以正常访问此方法'; + } +} +``` + +示例 +```javascript + +client.invoke('user_login',[]).then(function(ret){ + console.log(ret); +}); + +client.invoke('user_test',[]).then(function(ret){ + console.log(ret); +}); + +client.invoke('user_logout',[]).then(function(ret){ + console.log(ret); +}); + +``` \ No newline at end of file From dffb79e68ba5b0df822ec507800277707b5d03be Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:02:27 +0800 Subject: [PATCH 13/66] update readme --- README.md | 93 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 58 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index d25cbe6..e6d8d04 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,6 @@ -thinkphp5-helper -=================== -[![Latest Stable Version](https://poser.pugx.org/lobtao/thinkphp5-curl/v/stable)](https://packagist.org/packages/lobtao/thinkphp5-curl) -[![Total Downloads](https://poser.pugx.org/lobtao/thinkphp5-curl/downloads)](https://packagist.org/packages/lobtao/thinkphp5-curl) -[![License](https://poser.pugx.org/lobtao/thinkphp5-curl/license)](https://packagist.org/packages/lobtao/thinkphp5-curl) - -Easy working cURL extension for thinkphp5, including RESTful support: - - - POST - - GET - - HEAD - - PUT - - PATCH - - DELETE - -Requirements ------------- -- PHP 5.4+ -- Curl and php-curl installed - - -Installation ------------- - -The preferred way to install this extension is through [composer](http://getcomposer.org/download/). - -```bash -php composer.phar require --prefer-dist lobtao/thinkphp5-curl "*" -``` - - -Usage +Curl.php 使用示例 ----- -Once the extension is installed, simply use it in your code. The following example shows you how to handling a simple GET Request. - ```php use lobtao\thinkphp5\curl; $curl = new curl\Curl(); @@ -142,7 +109,7 @@ var_dump($curl->responseHeaders); RpcController.php RPC远程调用示例 ----- -ServiceController.php 服务提供接口 +ServiceController.php 服务控制器类 ```php namespace app\index\controller; @@ -189,9 +156,65 @@ class UserService { } ``` +server.js +```javascript +function client(baseUrl){ + var client = { + ajax: function (func, args, dataType) { + var _this = this; + var def = $.Deferred(); + $.ajax({ + type: "POST", + url: baseUrl, + data: {f: func, p: JSON.stringify(args)}, + success: function (ret) { + if (ret.retid == 0) { + if (_this.onerror) { + _this.onerror(ret.retmsg) + } + def.reject(ret.retmsg); + } else { + + def.resolve(ret.data); + } + }, + dataType: dataType + }); + return def; + }, + onerror: null, + invoke: function (func, args, callback) { + var promise = this.ajax(func, args, 'json'); + if (callback) { + promise.then(callback); + } + return promise; + }, + invokep: function (func, args, callback) { + var promise = this.ajax(func, args, 'jsonp'); + if (callback) { + promise.then(callback); + } + return promise; + } + }; + //全局异常处理 + client.onerror = function (err) { + alert(err); + }; + + return client; +} +``` + 示例 ```javascript +var client = client("http://localhost/testpro/index.php/index/service/index");//服务控制类地址 +client.invoke('test_hello',[]).then(function(ret){ + console.log(ret) +}); + client.invoke('user_login',[]).then(function(ret){ console.log(ret); }); From 1ad29d2d82ac1bf9ddd10bd9b1f3b0f93e152e89 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:04:06 +0800 Subject: [PATCH 14/66] update readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e6d8d04..d55d5d7 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ switch ($curl->responseCode) { var_dump($curl->responseHeaders); ``` -RpcController.php RPC远程调用示例 +RpcController.php 远程调用示例 ----- ServiceController.php 服务控制器类 @@ -211,6 +211,7 @@ function client(baseUrl){ ```javascript var client = client("http://localhost/testpro/index.php/index/service/index");//服务控制类地址 + client.invoke('test_hello',[]).then(function(ret){ console.log(ret) }); From 3f38cb49f15a8c3b7649df5e30d4098f80bc3c9a Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:05:00 +0800 Subject: [PATCH 15/66] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d55d5d7..330bdbd 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ function client(baseUrl){ } ``` -示例 +js调用后端PHP服务示例 ```javascript var client = client("http://localhost/testpro/index.php/index/service/index");//服务控制类地址 From 93f03fe6769d47136dc7e8cd7d67d0b0c688f09c Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:05:58 +0800 Subject: [PATCH 16/66] add readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 330bdbd..2667cdd 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ function client(baseUrl){ } ``` -js调用后端PHP服务示例 +js调用后端PHP服务类示例 ```javascript var client = client("http://localhost/testpro/index.php/index/service/index");//服务控制类地址 From 7d8b09a60ecaa1776e4eac72bf5f6a00ca2555e7 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:09:50 +0800 Subject: [PATCH 17/66] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2667cdd..d3871e6 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ class UserService { } ``` -server.js +server.js 依赖jquery.js ```javascript function client(baseUrl){ var client = { From 9f5a9330d888144e97cfc699bdc6ba5a519ce69d Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:33:58 +0800 Subject: [PATCH 18/66] update readme --- README.md | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d3871e6..1bd999f 100644 --- a/README.md +++ b/README.md @@ -141,11 +141,11 @@ namespace app\service; use think\Session; class UserService { - function login(){ + function login($params){ Session::set('user', ['name'=>'远思']); } - function logout(){ + function logout($params){ Session::delete('user'); Session::destroy(); } @@ -207,7 +207,7 @@ function client(baseUrl){ } ``` -js调用后端PHP服务类示例 +js调用后端PHP服务类示例,先引入server.js ```javascript var client = client("http://localhost/testpro/index.php/index/service/index");//服务控制类地址 @@ -216,7 +216,10 @@ client.invoke('test_hello',[]).then(function(ret){ console.log(ret) }); -client.invoke('user_login',[]).then(function(ret){ +client.invoke('user_login',[{ + name:'用户名', + password:'密码', +}]).then(function(ret){ console.log(ret); }); @@ -224,8 +227,81 @@ client.invoke('user_test',[]).then(function(ret){ console.log(ret); }); -client.invoke('user_logout',[]).then(function(ret){ +client.invoke('user_logout',[{ + name:'用户名', + }]).then(function(ret){ console.log(ret); }); +``` + +小程序调用 +client.js +```javascript +var baseUrl = 'https://xcx.go2carcare.com/index.php';//远程网址 +var serviceUrl = baseUrl + '/rpc/index';//rpc服务地址 +var upfileUrl = baseUrl + '/file/up';//文件上传地址 +var upfilesUrl = baseUrl + '/file/ups';//文件上传地址 + +function invoke(func, args, callback) { + wx.request({ + url: serviceUrl, + data: { + f: func, + p: JSON.stringify(args) + }, + header: { + "Content-Type": "application/x-www-form-urlencoded" + }, + dataType: 'json', + method: 'POST', + success: function (ret) { + //console.log('request返回值:', ret); + if (ret.data.retid == 1) { + callback(ret.data.data); + } else { + wx.showModal({ + showCancel: false, + confirmColor: '#ea644a', + //content: typeof ret.data == 'string' ? ret.data : func + ': ' + ret.data.retmsg, + content: typeof ret.data == 'string' ? ret.data : ret.data.retmsg, + }); + } + }, + complete:function(){ + // wx.hideLoading(); + // wx.hideToast(); + // wx.hideNavigationBarLoading(); + }, + }) +} + +module.exports = { + invoke: invoke, + upfileUrl: upfileUrl, + upfilesUrl:upfilesUrl +} +``` + +调用示例 +```javascript + +var client = require('client.js'); + +client.invoke('user_login', [{ + name:'用户名', + password:'用户名', +}], function (ret) { + console.log(ret); +}); + +client.invoke('user_test', [], function (ret) { + console.log(ret); +}); + +client.invoke('user_logout', [{ + name:'用户名', +}], function (ret) { + console.log(ret); +}); ``` \ No newline at end of file From 97d2b8dd3a3a01d7b108674f5dbec06c3b0bcceb Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:35:12 +0800 Subject: [PATCH 19/66] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1bd999f..5ef5b12 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ client.invoke('user_logout',[{ 小程序调用 client.js ```javascript -var baseUrl = 'https://xcx.go2carcare.com/index.php';//远程网址 +var baseUrl = 'http://localhost/testpro/index.php/index/service/index';//服务控制类地址 var serviceUrl = baseUrl + '/rpc/index';//rpc服务地址 var upfileUrl = baseUrl + '/file/up';//文件上传地址 var upfilesUrl = baseUrl + '/file/ups';//文件上传地址 From ba8d00695a122ba28bea06a7b1d43e01534f5ef8 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:36:33 +0800 Subject: [PATCH 20/66] update readme --- README.md | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5ef5b12..e912a4d 100644 --- a/README.md +++ b/README.md @@ -238,10 +238,7 @@ client.invoke('user_logout',[{ 小程序调用 client.js ```javascript -var baseUrl = 'http://localhost/testpro/index.php/index/service/index';//服务控制类地址 -var serviceUrl = baseUrl + '/rpc/index';//rpc服务地址 -var upfileUrl = baseUrl + '/file/up';//文件上传地址 -var upfilesUrl = baseUrl + '/file/ups';//文件上传地址 +var serviceUrl = 'http://localhost/testpro/index.php/index/service/index';//服务控制类地址 function invoke(func, args, callback) { wx.request({ @@ -256,30 +253,23 @@ function invoke(func, args, callback) { dataType: 'json', method: 'POST', success: function (ret) { - //console.log('request返回值:', ret); if (ret.data.retid == 1) { callback(ret.data.data); } else { wx.showModal({ showCancel: false, confirmColor: '#ea644a', - //content: typeof ret.data == 'string' ? ret.data : func + ': ' + ret.data.retmsg, content: typeof ret.data == 'string' ? ret.data : ret.data.retmsg, }); } }, complete:function(){ - // wx.hideLoading(); - // wx.hideToast(); - // wx.hideNavigationBarLoading(); }, }) } module.exports = { - invoke: invoke, - upfileUrl: upfileUrl, - upfilesUrl:upfilesUrl + invoke: invoke } ``` From 26b97c9f888f659e29ba9e8e8133fec5f22f305e Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:39:05 +0800 Subject: [PATCH 21/66] update readme --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e912a4d..76bb98f 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ class UserService { } ``` -server.js 依赖jquery.js +js端调用server.js库 依赖jquery.js ```javascript function client(baseUrl){ var client = { @@ -235,8 +235,7 @@ client.invoke('user_logout',[{ ``` -小程序调用 -client.js +小程序调用 client.js 库 ```javascript var serviceUrl = 'http://localhost/testpro/index.php/index/service/index';//服务控制类地址 From bd3721b62fd800d9b9dbb2b4c48bfd201b5dc537 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 1 Jun 2017 17:45:14 +0800 Subject: [PATCH 22/66] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 76bb98f..eb54013 100644 --- a/README.md +++ b/README.md @@ -279,7 +279,7 @@ var client = require('client.js'); client.invoke('user_login', [{ name:'用户名', - password:'用户名', + password:'密码', }], function (ret) { console.log(ret); }); From 9466da82ae7135f42176ead1e015207c30ccba07 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 22 Jun 2017 16:18:24 +0800 Subject: [PATCH 23/66] fix bugs fix bugs --- src/RpcController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/RpcController.php b/src/RpcController.php index fc9a565..087fc2d 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -20,7 +20,7 @@ public function handle($namespace,$filter=null) { $this->namespace = $namespace; $request = $this->request; - if ($request->isGet()) return 'API服务接口'; + //if ($request->isGet()) return 'API服务接口'; //异常拦截 error_reporting(E_ERROR); From 36c3cafa1827163b8295a7d1bd0c7d799f846183 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 12:05:31 +0800 Subject: [PATCH 24/66] add RpcException add RpcException --- src/RpcException.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/RpcException.php diff --git a/src/RpcException.php b/src/RpcException.php new file mode 100644 index 0000000..11bf2c3 --- /dev/null +++ b/src/RpcException.php @@ -0,0 +1,15 @@ + Date: Tue, 11 Jul 2017 12:26:44 +0800 Subject: [PATCH 25/66] add RpcException add RpcException --- src/RpcController.php | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 087fc2d..f784e90 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -2,9 +2,11 @@ namespace lobtao\tp5helper; use think\Controller; +use think\Log; use think\Response; -class RpcController extends Controller { +class RpcController extends Controller +{ private $func; private $args; @@ -16,7 +18,7 @@ class RpcController extends Controller { * @return string|\think\response\Json|\think\response\Jsonp * @throws \Exception */ - public function handle($namespace,$filter=null) { + public function handle($namespace, $filter = null) { $this->namespace = $namespace; $request = $this->request; @@ -35,8 +37,8 @@ public function handle($namespace,$filter=null) { $this->callback = $request->param('callback'); //过滤处理 - if($filter){ - call_user_func_array($filter, [$this->func,$this->args]); + if ($filter) { + call_user_func_array($filter, [$this->func, $this->args]); } $result = $this->callFunc($this->func, $this->args); @@ -56,12 +58,18 @@ public function handle($namespace,$filter=null) { * @return String */ function exception_handler($exception) { - $errMsg = $exception->getMessage(); - $response = $this->ajaxReturn([ - 'retid' => 0, - 'retmsg' => $errMsg, - ], $this->callback); - $response->send(); + if ($exception instanceof RpcException) { + $errMsg = $exception->getMessage(); + $response = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); + $response->send(); + } else { + Log::error('File: '.$exception->getFile()); + Log::error('Line: '.$exception->getLine().' 行'); + Log::error('Message: '.$exception->getMessage()); + } } /** From 67e70f0e6e9ae697845749dff5d474fc473cdb2d Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 12:31:31 +0800 Subject: [PATCH 26/66] add RpcException add RpcException --- src/RpcController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index f784e90..bb38116 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -65,11 +65,11 @@ function exception_handler($exception) { 'retmsg' => $errMsg, ], $this->callback); $response->send(); - } else { - Log::error('File: '.$exception->getFile()); - Log::error('Line: '.$exception->getLine().' 行'); - Log::error('Message: '.$exception->getMessage()); } + Log::error('Class: ' . get_class($exception)); + Log::error('File: ' . $exception->getFile()); + Log::error('Line: ' . $exception->getLine() . ' 行'); + Log::error('Message: ' . $exception->getMessage()); } /** From 1859cde9f39b545e123d567277488755582a61d9 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 12:38:12 +0800 Subject: [PATCH 27/66] update RpcException update RpcException --- src/RpcController.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index bb38116..3a05f26 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -60,16 +60,19 @@ public function handle($namespace, $filter = null) { function exception_handler($exception) { if ($exception instanceof RpcException) { $errMsg = $exception->getMessage(); - $response = $this->ajaxReturn([ - 'retid' => 0, - 'retmsg' => $errMsg, - ], $this->callback); - $response->send(); + } else { + $errMsg = '系统异常'; } + $response = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); + $response->send(); + Log::error('Class: ' . get_class($exception)); Log::error('File: ' . $exception->getFile()); Log::error('Line: ' . $exception->getLine() . ' 行'); - Log::error('Message: ' . $exception->getMessage()); + Log::error('系统异常: ' . $exception->getMessage()); } /** From acfb57b6a10f728b06997a77d7dfdf5ad49da3bc Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 15:07:55 +0800 Subject: [PATCH 28/66] fix RpcException bug fix RpcException bug --- src/Helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Helper.php b/src/Helper.php index 41c28d6..f67a3dc 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -41,7 +41,7 @@ function V($validate, $scenario, $params, $showException = true) { if (!$validate->scene($scenario)->check($params)) { $msg = $validate->getError(); - if ($showException) throw new \Exception($msg); + if ($showException) throw new \lobtao\tp5helper\RpcException($msg); } return $msg; } From 2119bd8c8217230e588bdeb2dd6a8ea49057c5a7 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 15:13:06 +0800 Subject: [PATCH 29/66] fix RpcException bug fix RpcException bug --- src/RpcController.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 3a05f26..6366613 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -84,14 +84,14 @@ function exception_handler($exception) { */ private function callFunc($func, $args) { $params = explode('_', $func, 2); - if (count($params) != 2) throw new \Exception('请求参数错误'); + if (count($params) != 2) throw new RpcException('请求参数错误'); $svname = ucfirst($params[0]); $classname = $this->namespace . $svname . 'Service'; $funcname = $params[1]; - if (!class_exists($classname)) throw new \Exception('类' . $svname . '不存在!!!'); + if (!class_exists($classname)) throw new RpcException('类' . $svname . '不存在!!!'); $object = new $classname(); - if (!method_exists($object, $funcname)) throw new \Exception($svname . '中不存在' . $funcname . '方法'); + if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); $data = call_user_func_array([$object, $funcname], $args); return $data; } From 247b275b7d82f878edd2733088771c444b0847fa Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 11 Jul 2017 15:14:46 +0800 Subject: [PATCH 30/66] fix RpcException bug fix RpcException bug --- src/RpcController.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 6366613..0936cfd 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -15,8 +15,8 @@ class RpcController extends Controller /** * 主方法 - * @return string|\think\response\Json|\think\response\Jsonp - * @throws \Exception + * @param $namespace + * @param null $filter */ public function handle($namespace, $filter = null) { $this->namespace = $namespace; @@ -54,8 +54,7 @@ public function handle($namespace, $filter = null) { /** * 异常拦截回复 - * @param \Exception $exception - * @return String + * @param $exception */ function exception_handler($exception) { if ($exception instanceof RpcException) { @@ -80,7 +79,6 @@ function exception_handler($exception) { * @param $func * @param $args * @return mixed - * @throws \Exception */ private function callFunc($func, $args) { $params = explode('_', $func, 2); From 9010d50767071bf4c201177da0ced8beebd7b707 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 12 Jul 2017 17:56:02 +0800 Subject: [PATCH 31/66] fix RpcException bug fix RpcException bug --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eb54013..e46fc5b 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ class ServiceController extends RpcController { return; if(!Session::get('user')){ - throw new \Exception('尚未登录,不能访问'); + throw new RpcException('尚未登录,不能访问'); } }); } From 3f8488f185b5a5a9cc30a23f854b703dd5c28907 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 12 Jul 2017 17:56:32 +0800 Subject: [PATCH 32/66] fix RpcException bug fix RpcException bug --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e46fc5b..1342a95 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ ServiceController.php 服务控制器类 namespace app\index\controller; use lobtao\tp5helper\RpcController; +use lobtao\tp5helper\RpcException; use think\Session; class ServiceController extends RpcController { From 0dee61b11546636cfdadf4a8ce489792cdcbf0c4 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 12 Jul 2017 18:01:08 +0800 Subject: [PATCH 33/66] update demo update demo --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 1342a95..ac76d4a 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,9 @@ class UserService { } ``` + +web端js调用示例 +----- js端调用server.js库 依赖jquery.js ```javascript function client(baseUrl){ @@ -236,6 +239,8 @@ client.invoke('user_logout',[{ ``` +小程序调用示例 +----- 小程序调用 client.js 库 ```javascript var serviceUrl = 'http://localhost/testpro/index.php/index/service/index';//服务控制类地址 From 9d7d36e7453ece983828e52ab075ca806e9725ab Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 26 Jul 2017 21:04:06 +0800 Subject: [PATCH 34/66] add workerman rpc add workerman rpc --- src/WorkerRpc.php | 128 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 src/WorkerRpc.php diff --git a/src/WorkerRpc.php b/src/WorkerRpc.php new file mode 100644 index 0000000..2c71ed9 --- /dev/null +++ b/src/WorkerRpc.php @@ -0,0 +1,128 @@ +con = $con; + $this->namespace = $namespace; + //if ($request->isGet()) return 'API服务接口'; + + //异常拦截 +// error_reporting(E_ERROR); +// set_RpcException_handler([$this, "RpcException_handler"]); + + $this->func = isset($_GET['f']) ? $_GET['f'] : ''; + $this->args = isset($_GET['p']) ? $_GET['p'] : []; + + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = json_decode($this->args, true); + } + $this->callback = isset($_GET['callback']) ? $_GET['callback'] : ''; + + //过滤处理 + if ($filter) { + call_user_func_array($filter, [$this->func, $this->args]); + } + $result = $this->callFunc($this->func, $this->args); + $response = $this->ajaxReturn( + [ + 'data' => $result,//返回数据 + 'retid' => 1,//调用成功标识 + ], + $this->callback//jsonp调用时的回调函数 + ); + $this->con->send($response); + } + + /** + * 异常拦截回复 + * @param RpcException $RpcException + * @return String + */ + function RpcException_handler($RpcException) { + $errMsg = $RpcException->getMessage(); + $response = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); + $this->con->send($response); + } + + /** + * 以‘-’来分割ajax传递过来的类名和方法名,调用该方法,并返回值 + * @param $func + * @param $args + * @return mixed + * @throws RpcException + */ + private function callFunc($func, $args) { + $params = explode('_', $func, 2); + if (count($params) != 2) throw new RpcException('请求参数错误'); + + $svname = ucfirst($params[0]); + $classname = $this->namespace . $svname . 'Service'; + $funcname = $params[1]; + if (!class_exists($classname)) throw new RpcException('类' . $svname . '不存在!'); + +// global $objects; +// $object = $objects[$classname]; +// if(!$objects[$classname]) { +// $object = new $classname(); +// $objects[$classname] = $object; +// } + $object = new $classname(); + + if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); + + //if(!$this->is_assoc($args)) throw new RpcException('参数格式错误!');//必须为序号数组嵌入一个对象[{"name":"xiao"}] +// $data = $object->$funcname($args[0]); + + $data = call_user_func_array([$object, $funcname], $args); + + return $data; + } + + /** + * ajax返回 + * @param $result + * @param $callback + * @return \think\response\Json|\think\response\Jsonp + */ + private function ajaxReturn($result, $callback) { + $data = json_encode($result); + return $callback ? sprintf('%s(%s)',$callback,$data) : $data; + } + + /** + * 判断是否为序号数组 + * @param $arr + * @return bool + */ + function is_assoc($arr) { + return array_keys($arr) !== range(0, count($arr) - 1); + } +} \ No newline at end of file From b505a3d07b779416a53afb866a87a64ac49840d6 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 27 Jul 2017 12:16:09 +0800 Subject: [PATCH 35/66] add workerman rpc add workerman rpc --- src/RpcController.php | 6 ++-- src/WorkerRpc.php | 71 ++++++++++++++++++++++++------------------- 2 files changed, 41 insertions(+), 36 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 0936cfd..d9551f5 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -68,10 +68,8 @@ function exception_handler($exception) { ], $this->callback); $response->send(); - Log::error('Class: ' . get_class($exception)); - Log::error('File: ' . $exception->getFile()); - Log::error('Line: ' . $exception->getLine() . ' 行'); - Log::error('系统异常: ' . $exception->getMessage()); + $msg = sprintf("Class: %s\nFile: %s\nLine: %s\n异常描述: %s\n",get_class($exception),$exception->getFile(),$exception->getLine(), $exception->getMessage()); + Log::error($msg); } /** diff --git a/src/WorkerRpc.php b/src/WorkerRpc.php index 2c71ed9..0ae920b 100644 --- a/src/WorkerRpc.php +++ b/src/WorkerRpc.php @@ -8,6 +8,7 @@ namespace lobtao\tp5helper; +use think\Log; use Workerman\Connection\TcpConnection; class WorkerRpc @@ -31,45 +32,54 @@ public function handle(TcpConnection $con, $namespace, $filter = null) { $this->namespace = $namespace; //if ($request->isGet()) return 'API服务接口'; - //异常拦截 -// error_reporting(E_ERROR); -// set_RpcException_handler([$this, "RpcException_handler"]); - - $this->func = isset($_GET['f']) ? $_GET['f'] : ''; - $this->args = isset($_GET['p']) ? $_GET['p'] : []; - - if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 - $this->args = json_decode($this->args, true); - } - $this->callback = isset($_GET['callback']) ? $_GET['callback'] : ''; - - //过滤处理 - if ($filter) { - call_user_func_array($filter, [$this->func, $this->args]); + //异常捕获 + try { + $this->func = isset($_REQUEST['f']) ? $_REQUEST['f'] : ''; + $this->args = isset($_REQUEST['p']) ? $_REQUEST['p'] : []; + + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = json_decode($this->args, true); + } + $this->callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : ''; + + //过滤处理 + if ($filter) { + call_user_func_array($filter, [$this->func, $this->args]); + } + $result = $this->callFunc($this->func, $this->args); + + $response = $this->ajaxReturn( + [ + 'data' => $result,//返回数据 + 'retid' => 1,//调用成功标识 + ], + $this->callback//jsonp调用时的回调函数 + ); + $this->con->send($response); + }catch(\Exception $ex){ + $this->exception_handler($ex); } - $result = $this->callFunc($this->func, $this->args); - $response = $this->ajaxReturn( - [ - 'data' => $result,//返回数据 - 'retid' => 1,//调用成功标识 - ], - $this->callback//jsonp调用时的回调函数 - ); - $this->con->send($response); } /** * 异常拦截回复 - * @param RpcException $RpcException + * @param RpcException $exception * @return String */ - function RpcException_handler($RpcException) { - $errMsg = $RpcException->getMessage(); + function exception_handler($exception) { + if ($exception instanceof RpcException) { + $errMsg = $exception->getMessage(); + } else { + $errMsg = '系统异常'; + } $response = $this->ajaxReturn([ 'retid' => 0, 'retmsg' => $errMsg, ], $this->callback); $this->con->send($response); + + $msg = sprintf("Class: %s\nFile: %s\nLine: %s\n异常描述: %s\n",get_class($exception),$exception->getFile(),$exception->getLine(), $exception->getMessage()); + Log::error($msg); } /** @@ -98,9 +108,6 @@ private function callFunc($func, $args) { if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); - //if(!$this->is_assoc($args)) throw new RpcException('参数格式错误!');//必须为序号数组嵌入一个对象[{"name":"xiao"}] -// $data = $object->$funcname($args[0]); - $data = call_user_func_array([$object, $funcname], $args); return $data; @@ -113,8 +120,8 @@ private function callFunc($func, $args) { * @return \think\response\Json|\think\response\Jsonp */ private function ajaxReturn($result, $callback) { - $data = json_encode($result); - return $callback ? sprintf('%s(%s)',$callback,$data) : $data; + $data = json_encode($result,JSON_UNESCAPED_UNICODE); + return $callback ? sprintf('%s(%s)', $callback, $data) : $data; } /** From 7a3f4f951a3581340aafa2a33d95f52b5ae6b303 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 27 Jul 2017 12:42:59 +0800 Subject: [PATCH 36/66] add workerman rpc add workerman rpc --- README.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ac76d4a..670039b 100644 --- a/README.md +++ b/README.md @@ -299,4 +299,59 @@ client.invoke('user_logout', [{ }], function (ret) { console.log(ret); }); -``` \ No newline at end of file +``` + +Workerman 提供Rpc服务 +----- +ServiceController.php 服务控制器类 + +```php +/** + * Created by lobtao. + * User: Administrator + * Date: 2017-7-26 + * Time: 16:51 + * workerman的性能是apache的239倍 + */ + +namespace app\admin\command; + +use lobtao\tp5helper\WorkerRpc; +use think\console\Command; +use think\console\Input; +use think\console\Output; +use Workerman\Connection\TcpConnection; +use Workerman\Protocols\Http; +use Workerman\Worker; + +class Api extends Command +{ + protected function configure() { + $this->setName('api') + ->addArgument('args') + ->addArgument('daemon') + ->setDescription('api接口调用'); + } + + protected function execute(Input $input, Output $output) { + global $argv; + array_shift($argv);//弹出第一个参数 + if ($argv[1] == 'startd') { + $argv[1] = 'start'; + $argv[2] = '-d'; + } + + $worker->onMessage = function (TcpConnection $con, $data) { + if($data['server']['REQUEST_URI'] == '/favicon.ico') return;//忽略favicon.ico请求 + Http::header('Access-Control-Allow-Origin:*');//允许前端跨域请求 + $rpc = new WorkerRpc(); + $rpc->handle($con, 'app\\service\\'); + }; + Worker::runAll(); + } +} + +./think api start +./think api startd +``` + From d7deb16d202235ea4f1a840e50fcf830bd12e84c Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 27 Jul 2017 12:44:21 +0800 Subject: [PATCH 37/66] add workerman rpc add workerman rpc --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 670039b..58642cf 100644 --- a/README.md +++ b/README.md @@ -351,7 +351,7 @@ class Api extends Command } } -./think api start -./think api startd ``` +./think api start //启动调试模式 +./think api startd //启动后台运行 From 6c4d3cb4f3871df03c3009ca4739eb8c0b9bc1a1 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 27 Jul 2017 12:45:03 +0800 Subject: [PATCH 38/66] add workerman rpc add workerman rpc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 58642cf..f20f036 100644 --- a/README.md +++ b/README.md @@ -354,4 +354,5 @@ class Api extends Command ``` ./think api start //启动调试模式 + ./think api startd //启动后台运行 From ff01650973c0c51f48e4f7b18e79c5dc5b9fe4ed Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 3 Oct 2017 21:29:50 +0800 Subject: [PATCH 39/66] remove extend Controller remove extend Controller --- src/Helper.php | 20 ++++++++++++++++++++ src/RpcController.php | 5 ++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index f67a3dc..abd8c7c 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -45,4 +45,24 @@ function V($validate, $scenario, $params, $showException = true) { } return $msg; } +} + +if (!function_exists('getValue')) { + /** + * 获取表单formData里字段值 + * @param $array + * @param $key + * @param int $type + * @return int|string + */ + function getValue($array, $key, $type = 0) { + switch ($type) { + case 0://字符串 + return array_key_exists($key, $array) ? $array[$key] : ''; + break; + case 1://整数、浮点数 + return array_key_exists($key, $array) ? $array[$key] : 0; + break; + } + } } \ No newline at end of file diff --git a/src/RpcController.php b/src/RpcController.php index d9551f5..ccccae7 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -1,11 +1,10 @@ namespace = $namespace; - $request = $this->request; + $request = request(); //if ($request->isGet()) return 'API服务接口'; //异常拦截 From c2f64750c03a1288b42de14f9ec55726607042f1 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 25 Oct 2017 15:00:08 +0800 Subject: [PATCH 40/66] add layout add layout --- src/Helper.php | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/Helper.php b/src/Helper.php index f67a3dc..20a9840 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -45,4 +45,63 @@ function V($validate, $scenario, $params, $showException = true) { } return $msg; } +} + +if (!function_exists('getValue')) { + /** + * 获取表单formData里字段值 + * @param $array + * @param $key + * @param int $type + * @return int|string + */ + function getValue($array, $key, $type = 0) { + switch ($type) { + case 0://字符串 + return array_key_exists($key, $array) ? $array[$key] : ''; + break; + case 1://整数、浮点数 + return array_key_exists($key, $array) ? $array[$key] : 0; + break; + } + } +} + +if (!function_exists('createUrl')) { + /** + * 生成url访问地址 + * @param $router + * @return string + */ + function createUrl($router) { + if (strpos($_SERVER['HTTP_USER_AGENT'], 'yssoft'))//需要在apicloud config.xml里配置 + return sprintf("func_openWin('%s','%s')", url($router, '', false, true), config('title')); + else + return url($router, '', false, true); + + } +} + +if (!function_exists('layout')) { + /** + * 布局母板页输出 + * @param string $template + * @param array $vars + * @param array $replace + * @param int $code + * @return $this|\think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml + */ + function layout($template = '', $vars = [], $replace = [], $code = 200) { + //渲染子页面 + $response = \think\Response::create($template, 'view', $code); + $response->replace($replace)->assign($vars); + //渲染母板页 + if (config('template.layout_on')) { + return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace([ + config('template.layout_item') => $response->getContent() + ]); + } else { + return $response; + } + } } \ No newline at end of file From 649726544570def1174894f807b1007c45f9032d Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 25 Oct 2017 15:08:14 +0800 Subject: [PATCH 41/66] add layout add layout --- src/Helper.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index b9c1bd0..20a9840 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -65,7 +65,6 @@ function getValue($array, $key, $type = 0) { break; } } -<<<<<<< HEAD } if (!function_exists('createUrl')) { @@ -105,6 +104,4 @@ function layout($template = '', $vars = [], $replace = [], $code = 200) { return $response; } } -======= ->>>>>>> ff01650973c0c51f48e4f7b18e79c5dc5b9fe4ed } \ No newline at end of file From 9240d3dce0a984d8c059a38d63249361d6fe75e0 Mon Sep 17 00:00:00 2001 From: lobtao Date: Sat, 28 Oct 2017 11:45:29 +0800 Subject: [PATCH 42/66] update layout --- src/Helper.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index 20a9840..c5e2c71 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -92,16 +92,12 @@ function createUrl($router) { * @return $this|\think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml */ function layout($template = '', $vars = [], $replace = [], $code = 200) { - //渲染子页面 - $response = \think\Response::create($template, 'view', $code); - $response->replace($replace)->assign($vars); - //渲染母板页 if (config('template.layout_on')) { return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace([ - config('template.layout_item') => $response->getContent() + config('template.layout_item') => (new \think\View(config('template')))->fetch($template, $vars,$replace) ]); } else { - return $response; + return \think\Response::create($template, 'view', $code); } } } \ No newline at end of file From d76ade42a768e18b3d7b9b34619f2399c47a89ab Mon Sep 17 00:00:00 2001 From: lobtao Date: Mon, 30 Oct 2017 22:31:59 +0800 Subject: [PATCH 43/66] update layout --- src/Helper.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index c5e2c71..b9cd925 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -77,7 +77,7 @@ function createUrl($router) { if (strpos($_SERVER['HTTP_USER_AGENT'], 'yssoft'))//需要在apicloud config.xml里配置 return sprintf("func_openWin('%s','%s')", url($router, '', false, true), config('title')); else - return url($router, '', false, true); + return sprintf("window.location.href='%s'", url($router, '', false, true)); } } @@ -94,7 +94,7 @@ function createUrl($router) { function layout($template = '', $vars = [], $replace = [], $code = 200) { if (config('template.layout_on')) { return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace([ - config('template.layout_item') => (new \think\View(config('template')))->fetch($template, $vars,$replace) + config('template.layout_item') => (new \think\View(config('template')))->fetch($template, $vars, $replace) ]); } else { return \think\Response::create($template, 'view', $code); From 2e925c2dd38b97bc50dc3e153a558370b21bb0c2 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 31 Oct 2017 00:08:37 +0800 Subject: [PATCH 44/66] update createUrl --- .DS_Store | Bin 0 -> 6148 bytes src/Helper.php | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5172429f264de2441865cb4700216d4256da9242 GIT binary patch literal 6148 zcmeH~J!%6%427R!7lt%jx}3%b$PET#pTHLgIFQEJ;E>dF^gR7ES*H$5cmnB-G%I%Z zD|S`@Z2$T80!#olbXV*=%*>dt@PRwdU#I)^a=X5>;#J@&VrHyNnC;iLL0pQvfVyTmjO&;ssLc!1UOG})p;=82 zR;?Ceh}WZ?+UmMqI#RP8R>OzYoz15hnq@nzF`-!xQ4j$Um=RcIKKc27r2jVm&svm< zfC&6E0=7P!4tu^-ovjbA=k?dB`g+i*aXG_}p8zI)6mRKa+;6_1_R^8c3Qa!(fk8n8 H{*=HsM+*^= literal 0 HcmV?d00001 diff --git a/src/Helper.php b/src/Helper.php index b9cd925..cc21ffd 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -75,9 +75,9 @@ function getValue($array, $key, $type = 0) { */ function createUrl($router) { if (strpos($_SERVER['HTTP_USER_AGENT'], 'yssoft'))//需要在apicloud config.xml里配置 - return sprintf("func_openWin('%s','%s')", url($router, '', false, true), config('title')); + return sprintf("func_openWin('%s','%s')", url($router, '', true, true), config('title')); else - return sprintf("window.location.href='%s'", url($router, '', false, true)); + return sprintf("window.location.href='%s'", url($router, '', true, true)); } } From cd9bd13a59d8f45b133ba4f135fe431a77fa5532 Mon Sep 17 00:00:00 2001 From: lobtao Date: Mon, 30 Oct 2017 11:10:09 -0500 Subject: [PATCH 45/66] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 5172429f264de2441865cb4700216d4256da9242..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~J!%6%427R!7lt%jx}3%b$PET#pTHLgIFQEJ;E>dF^gR7ES*H$5cmnB-G%I%Z zD|S`@Z2$T80!#olbXV*=%*>dt@PRwdU#I)^a=X5>;#J@&VrHyNnC;iLL0pQvfVyTmjO&;ssLc!1UOG})p;=82 zR;?Ceh}WZ?+UmMqI#RP8R>OzYoz15hnq@nzF`-!xQ4j$Um=RcIKKc27r2jVm&svm< zfC&6E0=7P!4tu^-ovjbA=k?dB`g+i*aXG_}p8zI)6mRKa+;6_1_R^8c3Qa!(fk8n8 H{*=HsM+*^= From fad5ca34e7902c0388df6b86b55a5fb7f5a163ce Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 1 Nov 2017 15:34:06 +0800 Subject: [PATCH 46/66] update layout --- src/Helper.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index cc21ffd..5f004b8 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -93,9 +93,10 @@ function createUrl($router) { */ function layout($template = '', $vars = [], $replace = [], $code = 200) { if (config('template.layout_on')) { - return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace([ - config('template.layout_item') => (new \think\View(config('template')))->fetch($template, $vars, $replace) + $replace = array_merge($replace,[ + config('template.layout_item') => \think\View::instance(config('template'))->fetch($template, $vars, $replace) ]); + return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace($replace); } else { return \think\Response::create($template, 'view', $code); } From 8efe487be623e050fb4081bc79dbe6f3849abaf8 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 18 Jan 2018 17:49:53 +0800 Subject: [PATCH 47/66] update helper update helper --- src/Helper.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index 5f004b8..282cd95 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -74,11 +74,18 @@ function getValue($array, $key, $type = 0) { * @return string */ function createUrl($router) { - if (strpos($_SERVER['HTTP_USER_AGENT'], 'yssoft'))//需要在apicloud config.xml里配置 - return sprintf("func_openWin('%s','%s')", url($router, '', true, true), config('title')); + $webview_type = request()->param('WEBVIEW_TYPE'); + $url = url($router, ['WEBVIEW_TYPE'=>$webview_type], true, true); + //1、小程序 + if($webview_type == 'miniprogram') + //公众号和小程序webview里都有MicroMessenger 安卓里有miniprogram iphone里没有miniprogram,所以增加参数WEBVIEW_TYPE区分是小程序里webview + return "wx.miniProgram.navigateTo({url: '/pages/webview/webview?url={$url}'})"; + //2、APP + else if (strpos($_SERVER['HTTP_USER_AGENT'], 'yssoft'))//需要在apicloud config.xml里配置 + return sprintf("func_openWin('%s','%s')", $url, config('title')); + //3、wap和公众号 else - return sprintf("window.location.href='%s'", url($router, '', true, true)); - + return sprintf("window.location.href='%s'", $url); } } From 5b5254f3eec6514453b1fb760a572b788d4c20e6 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 18 Jan 2018 18:44:07 +0800 Subject: [PATCH 48/66] update Helper.php update Helper.php --- src/Helper.php | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Helper.php b/src/Helper.php index 282cd95..2193548 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -75,9 +75,9 @@ function getValue($array, $key, $type = 0) { */ function createUrl($router) { $webview_type = request()->param('WEBVIEW_TYPE'); - $url = url($router, ['WEBVIEW_TYPE'=>$webview_type], true, true); + $url = url($router, ['WEBVIEW_TYPE' => $webview_type], true, true); //1、小程序 - if($webview_type == 'miniprogram') + if ($webview_type == 'miniprogram') //公众号和小程序webview里都有MicroMessenger 安卓里有miniprogram iphone里没有miniprogram,所以增加参数WEBVIEW_TYPE区分是小程序里webview return "wx.miniProgram.navigateTo({url: '/pages/webview/webview?url={$url}'})"; //2、APP @@ -100,7 +100,7 @@ function createUrl($router) { */ function layout($template = '', $vars = [], $replace = [], $code = 200) { if (config('template.layout_on')) { - $replace = array_merge($replace,[ + $replace = array_merge($replace, [ config('template.layout_item') => \think\View::instance(config('template'))->fetch($template, $vars, $replace) ]); return \think\Response::create('./' . config('template.layout_name'), 'view', $code)->replace($replace); @@ -108,4 +108,22 @@ function layout($template = '', $vars = [], $replace = [], $code = 200) { return \think\Response::create($template, 'view', $code); } } +} +if (!function_exists('layout')) { + function client_ip() { + $unknown = 'unknown'; + $ip = ''; + if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) { + $ip = $_SERVER['REMOTE_ADDR']; + } + /* + 处理多层代理的情况 + 或者使用正则方式:$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown; + */ + if (false !== strpos($ip, ',')) + $ip = reset(explode(',', $ip)); + return $ip; + } } \ No newline at end of file From d4065cc684dff1e5810bb67ef6ea971497851a53 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 18 Jan 2018 18:57:52 +0800 Subject: [PATCH 49/66] update Helper.php update Helper.php --- src/Helper.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Helper.php b/src/Helper.php index 2193548..8bcc9c5 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -109,7 +109,7 @@ function layout($template = '', $vars = [], $replace = [], $code = 200) { } } } -if (!function_exists('layout')) { +if (!function_exists('client_ip')) { function client_ip() { $unknown = 'unknown'; $ip = ''; From 9ddaf99a0af075749d5f5667cf383d6bcc4b5b18 Mon Sep 17 00:00:00 2001 From: lobtao Date: Tue, 24 Apr 2018 13:17:24 +0800 Subject: [PATCH 50/66] =?UTF-8?q?fix=20Log=E8=AE=B0=E5=BD=95=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix Log记录异常 --- src/RpcController.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index ccccae7..f21d0e8 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -65,10 +65,14 @@ function exception_handler($exception) { 'retid' => 0, 'retmsg' => $errMsg, ], $this->callback); + + $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(),get_class($exception),$exception->getFile(),$exception->getLine(), $exception->getMessage()); + if( class_exists('\think\facade\Log') ) { + \think\facade\Log::error($msg); + }else{ + \think\Log::error($msg); + } $response->send(); - - $msg = sprintf("Class: %s\nFile: %s\nLine: %s\n异常描述: %s\n",get_class($exception),$exception->getFile(),$exception->getLine(), $exception->getMessage()); - Log::error($msg); } /** From eb8c9b9117ec83c39a99db495eb2d1947f86851e Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 25 Apr 2018 10:28:01 +0800 Subject: [PATCH 51/66] =?UTF-8?q?fix=205.1=20Log=E7=9A=84=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix 5.1 Log的异常 --- .gitignore | 2 + src/RpcController.php | 93 +++++++++++++++++++++---------------------- 2 files changed, 47 insertions(+), 48 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9bea433 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +.DS_Store diff --git a/src/RpcController.php b/src/RpcController.php index f21d0e8..14b2a90 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -4,8 +4,7 @@ use think\Log; use think\Response; -class RpcController -{ +class RpcController { private $func; private $args; @@ -18,61 +17,57 @@ class RpcController * @param null $filter */ public function handle($namespace, $filter = null) { + $this->namespace = $namespace; $request = request(); //if ($request->isGet()) return 'API服务接口'; //异常拦截 - error_reporting(E_ERROR); - set_exception_handler([$this, "exception_handler"]); +// error_reporting(E_ERROR); +// set_exception_handler([$this, "exception_handler"]); + try { + $this->func = $request->param('f'); + $this->args = $request->param('p', []); - $this->func = $request->param('f'); - $this->args = $request->param('p', []); + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = json_decode($this->args, true); + } + $this->callback = $request->param('callback'); - if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 - $this->args = json_decode($this->args, true); - } - $this->callback = $request->param('callback'); + //过滤处理 + if ($filter) { + call_user_func_array($filter, [$this->func, $this->args]); + } - //过滤处理 - if ($filter) { - call_user_func_array($filter, [$this->func, $this->args]); - } - - $result = $this->callFunc($this->func, $this->args); - $response = $this->ajaxReturn( - [ - 'data' => $result,//返回数据 - 'retid' => 1,//调用成功标识 - ], - $this->callback//jsonp调用时的回调函数 - ); - $response->send(); - } + $result = $this->callFunc($this->func, $this->args); + $response = $this->ajaxReturn( + [ + 'data' => $result,//返回数据 + 'retid' => 1,//调用成功标识 + ], + $this->callback//jsonp调用时的回调函数 + ); + return $response; + } catch (\Exception $exception) { + if ($exception instanceof RpcException) { + $errMsg = $exception->getMessage(); + } else { + $errMsg = '系统异常'; + } + $response = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); - /** - * 异常拦截回复 - * @param $exception - */ - function exception_handler($exception) { - if ($exception instanceof RpcException) { - $errMsg = $exception->getMessage(); - } else { - $errMsg = '系统异常'; - } - $response = $this->ajaxReturn([ - 'retid' => 0, - 'retmsg' => $errMsg, - ], $this->callback); - - $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(),get_class($exception),$exception->getFile(),$exception->getLine(), $exception->getMessage()); - if( class_exists('\think\facade\Log') ) { - \think\facade\Log::error($msg); - }else{ - \think\Log::error($msg); + $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(), get_class($exception), $exception->getFile(), $exception->getLine(), $exception->getMessage()); + if (class_exists('\think\facade\Log')) { + \think\facade\Log::error($msg); + } else { + \think\Log::error($msg); + } + return $response; } - $response->send(); } /** @@ -82,12 +77,13 @@ function exception_handler($exception) { * @return mixed */ private function callFunc($func, $args) { + $params = explode('_', $func, 2); if (count($params) != 2) throw new RpcException('请求参数错误'); - $svname = ucfirst($params[0]); + $svname = ucfirst($params[0]); $classname = $this->namespace . $svname . 'Service'; - $funcname = $params[1]; + $funcname = $params[1]; if (!class_exists($classname)) throw new RpcException('类' . $svname . '不存在!!!'); $object = new $classname(); if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); @@ -102,6 +98,7 @@ private function callFunc($func, $args) { * @return \think\response\Json|\think\response\Jsonp */ private function ajaxReturn($result, $callback) { + return $callback ? jsonp($result) : json($result); } From 140b7ba911b105a42c60909488005891cc9e95cf Mon Sep 17 00:00:00 2001 From: lobtao Date: Fri, 27 Apr 2018 19:02:32 +0800 Subject: [PATCH 52/66] update workerman rpc --- src/BaseRpc.php | 92 +++++++++++++++++++++++++++++++++++++++++++ src/RpcController.php | 63 +++-------------------------- src/RpcWorker.php | 56 ++++++++++++++++++++++++++ 3 files changed, 153 insertions(+), 58 deletions(-) create mode 100644 src/BaseRpc.php create mode 100644 src/RpcWorker.php diff --git a/src/BaseRpc.php b/src/BaseRpc.php new file mode 100644 index 0000000..7edfff5 --- /dev/null +++ b/src/BaseRpc.php @@ -0,0 +1,92 @@ +getMessage(); + } else { + $errMsg = '系统异常'; + } + $data = $this->ajaxReturn([ + 'retid' => 0, + 'retmsg' => $errMsg, + ], $this->callback); + + + $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(), get_class($exception), $exception->getFile(), $exception->getLine(), $exception->getMessage()); + if (class_exists('\think\facade\Log')) { + \think\facade\Log::error($msg); + } else { + \think\Log::error($msg); + } + + return $data; + } + + /** + * 以‘-’来分割ajax传递过来的类名和方法名,调用该方法,并返回值 + * @param $func + * @param $args + * @return mixed + * @throws RpcException + */ + protected function callFunc($func, $args) { + + $params = explode('_', $func, 2); + if (count($params) != 2) throw new RpcException('请求参数错误'); + + $svname = ucfirst($params[0]); + $classname = $this->namespace . $svname . 'Service'; + $funcname = $params[1]; + if (!class_exists($classname)) throw new RpcException('类' . $classname . '不存在!'); + + $object = new $classname(); + if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); + $data = call_user_func_array([$object, $funcname], $args); + + return $data; + } + + /** + * ajax返回 + * @param $result + * @param $callback + * @return \think\response\Json|\think\response\Jsonp + */ + protected function ajaxReturn($result, $callback) { + + $data = json_encode($result, JSON_UNESCAPED_UNICODE); + return $callback ? sprintf('%s(%s)', $callback, $data) : $data; + } + + /** + * 判断是否为序号数组 + * @param $arr + * @return bool + */ + protected function is_assoc($arr) { + + return array_keys($arr) !== range(0, count($arr) - 1); + } +} \ No newline at end of file diff --git a/src/RpcController.php b/src/RpcController.php index 14b2a90..5a128af 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -4,17 +4,13 @@ use think\Log; use think\Response; -class RpcController { - - private $func; - private $args; - private $callback; - private $namespace; +class RpcController extends BaseRpc{ /** * 主方法 * @param $namespace * @param null $filter + * @return \think\response\Json|\think\response\Jsonp */ public function handle($namespace, $filter = null) { @@ -24,13 +20,12 @@ public function handle($namespace, $filter = null) { //if ($request->isGet()) return 'API服务接口'; //异常拦截 -// error_reporting(E_ERROR); -// set_exception_handler([$this, "exception_handler"]); try { $this->func = $request->param('f'); $this->args = $request->param('p', []); if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = html_entity_decode($this->args); $this->args = json_decode($this->args, true); } $this->callback = $request->param('callback'); @@ -49,57 +44,9 @@ public function handle($namespace, $filter = null) { $this->callback//jsonp调用时的回调函数 ); return $response; - } catch (\Exception $exception) { - if ($exception instanceof RpcException) { - $errMsg = $exception->getMessage(); - } else { - $errMsg = '系统异常'; - } - $response = $this->ajaxReturn([ - 'retid' => 0, - 'retmsg' => $errMsg, - ], $this->callback); - - $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(), get_class($exception), $exception->getFile(), $exception->getLine(), $exception->getMessage()); - if (class_exists('\think\facade\Log')) { - \think\facade\Log::error($msg); - } else { - \think\Log::error($msg); - } - return $response; + } catch (\Exception $ex) { + return $this->exception_handler($ex); } } - /** - * 以‘-’来分割ajax传递过来的类名和方法名,调用该方法,并返回值 - * @param $func - * @param $args - * @return mixed - */ - private function callFunc($func, $args) { - - $params = explode('_', $func, 2); - if (count($params) != 2) throw new RpcException('请求参数错误'); - - $svname = ucfirst($params[0]); - $classname = $this->namespace . $svname . 'Service'; - $funcname = $params[1]; - if (!class_exists($classname)) throw new RpcException('类' . $svname . '不存在!!!'); - $object = new $classname(); - if (!method_exists($object, $funcname)) throw new RpcException($svname . '中不存在' . $funcname . '方法'); - $data = call_user_func_array([$object, $funcname], $args); - return $data; - } - - /** - * ajax返回 - * @param $result - * @param $callback - * @return \think\response\Json|\think\response\Jsonp - */ - private function ajaxReturn($result, $callback) { - - return $callback ? jsonp($result) : json($result); - } - } \ No newline at end of file diff --git a/src/RpcWorker.php b/src/RpcWorker.php new file mode 100644 index 0000000..cb5fdf8 --- /dev/null +++ b/src/RpcWorker.php @@ -0,0 +1,56 @@ +namespace = $namespace; + //if ($request->isGet()) return 'API服务接口'; + + //异常捕获 + try { + $this->func = isset($_REQUEST['f']) ? $_REQUEST['f'] : ''; + $this->args = isset($_REQUEST['p']) ? $_REQUEST['p'] : []; + + if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 + $this->args = html_entity_decode($this->args); + $this->args = json_decode($this->args, true); + } + $this->callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : ''; + + //过滤处理 + if ($filter) { + call_user_func_array($filter, [$this->func, $this->args]); + } + $result = $this->callFunc($this->func, $this->args); + + $data = $this->ajaxReturn( + [ + 'data' => $result,//返回数据 + 'retid' => 1,//调用成功标识 + ], + $this->callback//jsonp调用时的回调函数 + ); + return $data; + }catch(\Exception $ex){ + return $this->exception_handler($ex); + } + } + +} \ No newline at end of file From de327ad6a0ddc9f23d73e75c11ae55ac65b48c1e Mon Sep 17 00:00:00 2001 From: lobtao Date: Sat, 28 Apr 2018 18:50:45 +0800 Subject: [PATCH 53/66] =?UTF-8?q?fix=20rpc=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix rpc判断 --- src/RpcController.php | 2 +- src/RpcWorker.php | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/RpcController.php b/src/RpcController.php index 5a128af..59a6a95 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -31,7 +31,7 @@ public function handle($namespace, $filter = null) { $this->callback = $request->param('callback'); //过滤处理 - if ($filter) { + if (isset($filter)) { call_user_func_array($filter, [$this->func, $this->args]); } diff --git a/src/RpcWorker.php b/src/RpcWorker.php index cb5fdf8..4c79090 100644 --- a/src/RpcWorker.php +++ b/src/RpcWorker.php @@ -16,8 +16,9 @@ class RpcWorker extends BaseRpc /** * 主方法 - * @return string|\think\response\Json|\think\response\Jsonp - * @throws RpcException + * @param $namespace + * @param null $filter + * @return String|\think\response\Json|\think\response\Jsonp */ public function handle( $namespace, $filter = null) { $this->namespace = $namespace; @@ -35,7 +36,7 @@ public function handle( $namespace, $filter = null) { $this->callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : ''; //过滤处理 - if ($filter) { + if (isset($filter)) { call_user_func_array($filter, [$this->func, $this->args]); } $result = $this->callFunc($this->func, $this->args); From d3e1aef5d8f8eb9d2027366966de020ebe5bd76d Mon Sep 17 00:00:00 2001 From: lobtao Date: Sat, 28 Apr 2018 19:42:53 +0800 Subject: [PATCH 54/66] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E6=8A=9B=E5=87=BA=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根据配置抛出错误 --- src/BaseRpc.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/BaseRpc.php b/src/BaseRpc.php index 7edfff5..0d21aaa 100644 --- a/src/BaseRpc.php +++ b/src/BaseRpc.php @@ -26,7 +26,11 @@ protected function exception_handler($exception) { if ($exception instanceof RpcException) { $errMsg = $exception->getMessage(); } else { - $errMsg = '系统异常'; + if(config('showerror')){ + $errMsg = $exception->getMessage(); + }else{ + $errMsg = '系统异常'; + } } $data = $this->ajaxReturn([ 'retid' => 0, From e28572286235f0722b27897b024f285def6bb10d Mon Sep 17 00:00:00 2001 From: lobtao Date: Fri, 11 May 2018 12:28:16 +0800 Subject: [PATCH 55/66] add PHPSocketIO add PHPSocketIO --- src/PHPSocketIO.php | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/PHPSocketIO.php diff --git a/src/PHPSocketIO.php b/src/PHPSocketIO.php new file mode 100644 index 0000000..575146f --- /dev/null +++ b/src/PHPSocketIO.php @@ -0,0 +1,36 @@ +io = new SocketIO($this->port, $this->opts); + // 初始化 + $this->init(); + // Run worker + Worker::runAll(); + } + + protected function init() { + } +} \ No newline at end of file From 270c1c256411355cc1d350152731a7dbde5e2a3c Mon Sep 17 00:00:00 2001 From: lobtao Date: Fri, 18 May 2018 12:50:10 +0800 Subject: [PATCH 56/66] update $io --- src/PHPSocketIO.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/PHPSocketIO.php b/src/PHPSocketIO.php index 575146f..87b2f5e 100644 --- a/src/PHPSocketIO.php +++ b/src/PHPSocketIO.php @@ -11,9 +11,8 @@ use PHPSocketIO\SocketIO; use Workerman\Worker; -abstract class PHPSocketIO -{ - protected $io; +abstract class PHPSocketIO { + public $io; protected $opts = []; protected $port = '9982'; From ab546fa21fd22c23b50e3010b3ecf3a8db4196b2 Mon Sep 17 00:00:00 2001 From: lobtao Date: Thu, 7 Jun 2018 22:33:40 +0800 Subject: [PATCH 57/66] update --- src/BaseRpc.php | 15 +++++++++------ src/RpcController.php | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/BaseRpc.php b/src/BaseRpc.php index 0d21aaa..66594a5 100644 --- a/src/BaseRpc.php +++ b/src/BaseRpc.php @@ -9,6 +9,7 @@ abstract class BaseRpc { + protected $func; protected $args; protected $callback; @@ -26,9 +27,9 @@ protected function exception_handler($exception) { if ($exception instanceof RpcException) { $errMsg = $exception->getMessage(); } else { - if(config('showerror')){ + if (config('showerror')) { $errMsg = $exception->getMessage(); - }else{ + } else { $errMsg = '系统异常'; } } @@ -41,7 +42,9 @@ protected function exception_handler($exception) { $msg = sprintf("Trace:%s\nClass: %s\nFile: %s\nLine: %s\n异常描述: %s", $exception->getTraceAsString(), get_class($exception), $exception->getFile(), $exception->getLine(), $exception->getMessage()); if (class_exists('\think\facade\Log')) { \think\facade\Log::error($msg); - } else { + } else if (class_exists('\workermvc\Log')) { + \workermvc\Log::error($msg); + } else if (is_callable(['\think\Log', 'error'])) { \think\Log::error($msg); } @@ -60,9 +63,9 @@ protected function callFunc($func, $args) { $params = explode('_', $func, 2); if (count($params) != 2) throw new RpcException('请求参数错误'); - $svname = ucfirst($params[0]); + $svname = ucfirst($params[0]); $classname = $this->namespace . $svname . 'Service'; - $funcname = $params[1]; + $funcname = $params[1]; if (!class_exists($classname)) throw new RpcException('类' . $classname . '不存在!'); $object = new $classname(); @@ -76,7 +79,7 @@ protected function callFunc($func, $args) { * ajax返回 * @param $result * @param $callback - * @return \think\response\Json|\think\response\Jsonp + * @return string */ protected function ajaxReturn($result, $callback) { diff --git a/src/RpcController.php b/src/RpcController.php index 59a6a95..04e36e3 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -10,7 +10,7 @@ class RpcController extends BaseRpc{ * 主方法 * @param $namespace * @param null $filter - * @return \think\response\Json|\think\response\Jsonp + * @return string */ public function handle($namespace, $filter = null) { From 5258598e151b2892f8af93315e962a82d1239aca Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 11 Jul 2018 16:10:27 +0800 Subject: [PATCH 58/66] Update Curl.php --- src/Curl.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Curl.php b/src/Curl.php index e52e58d..a1695a6 100644 --- a/src/Curl.php +++ b/src/Curl.php @@ -519,7 +519,7 @@ protected function _httpRequest($method, $raw = false) if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') { return true; } else { - $this->response = $raw ? $this->response : Json::decode($this->response); + $this->response = $raw ? $this->response : json_decode($this->response,true); return $this->response; } } @@ -599,4 +599,4 @@ protected function _extractCurlHeaders ($response) return $headers; } -} \ No newline at end of file +} From b7f7749245e80519faf86e465cbc49b64f6e23f7 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 11 Jul 2018 16:16:28 +0800 Subject: [PATCH 59/66] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f20f036..287b7b4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Curl.php 使用示例 ----- ```php -use lobtao\thinkphp5\curl; +use lobtao\tp5helper\curl; $curl = new curl\Curl(); //get http://example.com/ From 14e2eed3af985a8891755b31efcb39ce095cded3 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 11 Jul 2018 16:18:01 +0800 Subject: [PATCH 60/66] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 287b7b4..ab9462c 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ Curl.php 使用示例 ----- ```php -use lobtao\tp5helper\curl; -$curl = new curl\Curl(); +use lobtao\tp5helper\Curl; +$curl = new Curl(); //get http://example.com/ $response = $curl->get('http://example.com/'); @@ -24,7 +24,7 @@ if ($curl->errorCode === null) { ```php // GET request with GET params // http://example.com/?key=value&scondKey=secondValue -$curl = new curl\Curl(); +$curl = new Curl(); $response = $curl->setGetParams([ 'key' => 'value', 'secondKey' => 'secondValue' @@ -35,7 +35,7 @@ $response = $curl->setGetParams([ ```php // POST URL form-urlencoded -$curl = new curl\Curl(); +$curl = new Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' @@ -45,7 +45,7 @@ $response = $curl->setPostParams([ ```php // POST with special headers -$curl = new curl\Curl(); +$curl = new Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' @@ -59,7 +59,7 @@ $response = $curl->setPostParams([ ```php // POST JSON with body string & special headers -$curl = new curl\Curl(); +$curl = new Curl(); $params = [ 'key' => 'value', @@ -76,7 +76,7 @@ $response = $curl->setRequestBody(json_encode($params)) ```php // Avanced POST request with curl options & error handling -$curl = new curl\Curl(); +$curl = new Curl(); $params = [ 'key' => 'value', From a1ec3678086dbc37620c1353b185461f9bbda668 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 11 Jul 2018 16:37:41 +0800 Subject: [PATCH 61/66] update Curl.php --- src/Curl.php | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Curl.php b/src/Curl.php index a1695a6..017cdb0 100644 --- a/src/Curl.php +++ b/src/Curl.php @@ -72,19 +72,19 @@ class Curl * @var array HTTP-Status Code * Custom options holder */ - protected $_options = []; + protected $_options = array(); /** * @var array * Hold array of get params to send with the request */ - protected $_getParams = []; + protected $_getParams = array(); /** * @var array * Hold array of post params to send with the request */ - protected $_postParams = []; + protected $_postParams = array(); /** * @var resource|null @@ -102,13 +102,13 @@ class Curl * @var array default curl options * Default curl options */ - protected $_defaultOptions = [ + protected $_defaultOptions = array( CURLOPT_USERAGENT => 'thinkphp5-Curl-Agent', CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, - ]; + ); // ############################################### class methods // ############################################## @@ -325,7 +325,7 @@ public function setHeaders($headers) if (is_array($headers)) { //init - $parsedHeader = []; + $parsedHeader = array(); //parse header into right format key:value foreach ($headers as $header => $value) { @@ -370,7 +370,7 @@ public function unsetOptions() { //reset all options if (isset($this->_options)) { - $this->_options = []; + $this->_options = array(); } return $this; @@ -390,7 +390,7 @@ public function reset() //reset all options if (isset($this->_options)) { - $this->_options = []; + $this->_options = array(); } //reset response & status params @@ -402,8 +402,8 @@ public function reset() $this->responseLength = -1; $this->responseType = null; $this->errorText = null; - $this->_postParams = []; - $this->_getParams = []; + $this->_postParams = array(); + $this->_getParams = array(); return $this; } @@ -449,7 +449,7 @@ public function getInfo($opt = null) } elseif ($this->_curl !== null && $opt !== null) { return curl_getinfo($this->_curl, $opt); } else { - return []; + return array(); } } @@ -585,7 +585,7 @@ protected function _extractCurlBody ($response) protected function _extractCurlHeaders ($response) { //Init - $headers = []; + $headers = array(); $headerText = substr($response, 0, strpos($response, "\r\n\r\n")); foreach (explode("\r\n", $headerText) as $i => $line) { @@ -599,4 +599,4 @@ protected function _extractCurlHeaders ($response) return $headers; } -} +} \ No newline at end of file From 187244278d51499763c588d8bf0bdaf74faf74d6 Mon Sep 17 00:00:00 2001 From: lobtao Date: Wed, 16 Jan 2019 21:02:38 +0800 Subject: [PATCH 62/66] =?UTF-8?q?fix=20=E6=96=87=E6=9C=AC=E4=B8=AD?= =?UTF-8?q?=E5=8C=85=E5=90=AB=E5=8F=8C=E5=BC=95=E5=8F=B7=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix 文本中包含双引号问题 --- .gitignore | 6 ++++++ src/RpcController.php | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9bea433..8947473 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,8 @@ .DS_Store +.idea/encodings.xml +.idea/misc.xml +.idea/modules.xml +.idea/tp5helper.iml +.idea/vcs.xml +.idea/workspace.xml diff --git a/src/RpcController.php b/src/RpcController.php index 04e36e3..2d26283 100644 --- a/src/RpcController.php +++ b/src/RpcController.php @@ -25,7 +25,7 @@ public function handle($namespace, $filter = null) { $this->args = $request->param('p', []); if (gettype($this->args) == 'string') {//微信小程序特别设置;浏览器提交过来自动转换 - $this->args = html_entity_decode($this->args); + //$this->args = html_entity_decode($this->args);//chrome端加上这个会报错 $this->args = json_decode($this->args, true); } $this->callback = $request->param('callback'); From 4f37522a17c43bfdd5ed80414a47ecd7e37cee1f Mon Sep 17 00:00:00 2001 From: lobtao Date: Sun, 16 Jun 2019 06:11:55 +0800 Subject: [PATCH 63/66] Update BaseRpc.php --- src/BaseRpc.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/BaseRpc.php b/src/BaseRpc.php index 66594a5..fe4d334 100644 --- a/src/BaseRpc.php +++ b/src/BaseRpc.php @@ -83,8 +83,11 @@ protected function callFunc($func, $args) { */ protected function ajaxReturn($result, $callback) { - $data = json_encode($result, JSON_UNESCAPED_UNICODE); - return $callback ? sprintf('%s(%s)', $callback, $data) : $data; + // $data = json_encode($result, JSON_UNESCAPED_UNICODE); + // return $callback ? sprintf('%s(%s)', $callback, $data) : $data; + + return $callback ? jsonp($result) : json($result); + } /** From 131262f40bd8da3f125d1fe655c4cd03c3ae11ab Mon Sep 17 00:00:00 2001 From: lobtao Date: Sun, 16 Jun 2019 06:18:19 +0800 Subject: [PATCH 64/66] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ab9462c..8e0ed5e 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ use think\Session; class ServiceController extends RpcController { function index() { - $this->handle('app\\service\\', function ($func, $params) { + return $this->handle('app\\service\\', function ($func, $params) { if (in_array(strtolower($func), ['user_login', 'user_logout'])) //登录方法不判断 return; From ddcfab7ccd0145ce1f82622adbefbc91410c8dd2 Mon Sep 17 00:00:00 2001 From: lobtao Date: Sun, 19 Jan 2020 13:37:19 +0800 Subject: [PATCH 65/66] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8e0ed5e..39d6e38 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +composer require lobtao/tp5helper +----- Curl.php 使用示例 ----- From 5b092a37352921fb1f837376168a1c965792bccb Mon Sep 17 00:00:00 2001 From: lobtao Date: Sun, 19 Jan 2020 13:37:44 +0800 Subject: [PATCH 66/66] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 39d6e38..5748990 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ -composer require lobtao/tp5helper +安装 ----- +composer require lobtao/tp5helper + Curl.php 使用示例 -----