改进response类

This commit is contained in:
thinkphp
2016-05-11 14:04:56 +08:00
parent fce80eb623
commit 7f385217b9
7 changed files with 94 additions and 119 deletions

View File

@@ -371,12 +371,10 @@ function request()
} }
/** /**
* 设置Response输出 * 获取当前的Response对象实例
* @param string $name 方法 * @return \think\Response
* @param mixed $param 参数
* @return mixed
*/ */
function response($name, $param = '') function response()
{ {
return Response::$name($param); return Response::instance();
} }

View File

@@ -111,7 +111,7 @@ class App
// 监听app_end // 监听app_end
APP_HOOK && Hook::listen('app_end', $data); APP_HOOK && Hook::listen('app_end', $data);
// 自动响应输出 // 自动响应输出
return Response::send($data, '', Config::get('response_return')); return Response::instance()->send($data, '', Config::get('response_return'));
} }
} }
} }

View File

@@ -154,7 +154,7 @@ class Error
// 异常信息输出监听 // 异常信息输出监听
APP_HOOK && Hook::listen('error_output', $data); APP_HOOK && Hook::listen('error_output', $data);
// 输出异常内容 // 输出异常内容
Response::send($data, $type, Config::get('response_return')); Response::instance()->send($data, $type, Config::get('response_return'));
} else { } else {
//ob_end_clean(); //ob_end_clean();
extract($data); extract($data);

View File

@@ -16,17 +16,18 @@ use think\Url;
class Response class Response
{ {
protected static $instance;
// 输出数据的转换方法 // 输出数据的转换方法
protected static $transform = null; protected $transform = null;
// 输出数据 // 输出数据
protected static $data = ''; protected $data = '';
// 是否exit // 是否exit
protected static $isExit = false; protected $isExit = false;
// 输出类型 // 输出类型
protected static $type = ''; protected $type = '';
// contentType // contentType
protected static $contentType = [ protected $contentType = [
'json' => 'application/json', 'json' => 'application/json',
'xml' => 'text/xml', 'xml' => 'text/xml',
'html' => 'text/html', 'html' => 'text/html',
@@ -34,56 +35,30 @@ class Response
'script' => 'application/javascript', 'script' => 'application/javascript',
'text' => 'text/plain', 'text' => 'text/plain',
]; ];
// HTTP status
protected static $code = [ /**
// Informational 1xx * 架构函数
100 => 'Continue', * @access public
101 => 'Switching Protocols', * @param array $options 参数
// Success 2xx */
200 => 'OK', public function __construct($type = '')
201 => 'Created', {
202 => 'Accepted', $this->type = $type;
203 => 'Non-Authoritative Information', }
204 => 'No Content',
205 => 'Reset Content', /**
206 => 'Partial Content', * 初始化
// Redirection 3xx * @access public
300 => 'Multiple Choices', * @param string $type 输出类型
301 => 'Moved Permanently', * @return \think\Request
302 => 'Moved Temporarily ', // 1.1 */
303 => 'See Other', public static function instance($type = '')
304 => 'Not Modified', {
305 => 'Use Proxy', if (is_null(self::$instance)) {
// 306 is deprecated but reserved self::$instance = new static($type);
307 => 'Temporary Redirect', }
// Client Error 4xx return self::$instance;
400 => 'Bad Request', }
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
// Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded',
];
/** /**
* 发送数据到客户端 * 发送数据到客户端
@@ -93,20 +68,20 @@ class Response
* @param bool $return 是否返回数据 * @param bool $return 是否返回数据
* @return mixed * @return mixed
*/ */
public static function send($data = [], $type = '', $return = false) public function send($data = [], $type = '', $return = false)
{ {
if ('' == $type) { if ('' == $type) {
$type = self::$type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type')); $type = $this->type ?: (IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'));
} }
$type = strtolower($type); $type = strtolower($type);
$data = $data ?: self::$data; $data = $data ?: $this->data;
if (!headers_sent() && isset(self::$contentType[$type])) { if (!headers_sent() && isset($this->contentType[$type])) {
header('Content-Type:' . self::$contentType[$type] . '; charset=utf-8'); header('Content-Type:' . $this->contentType[$type] . '; charset=utf-8');
} }
if (is_callable(self::$transform)) { if (is_callable($this->transform)) {
$data = call_user_func_array(self::$transform, [$data]); $data = call_user_func_array($this->transform, [$data]);
} else { } else {
switch ($type) { switch ($type) {
case 'json': case 'json':
@@ -128,7 +103,7 @@ class Response
} }
echo $data; echo $data;
self::isExit() && exit(); $this->isExit() && exit();
} }
/** /**
@@ -137,9 +112,10 @@ class Response
* @param mixed $callback 调用的转换方法 * @param mixed $callback 调用的转换方法
* @return $this * @return $this
*/ */
public static function transform($callback) public function transform($callback)
{ {
self::$transform = $callback; $this->transform = $callback;
return $this;
} }
/** /**
@@ -148,34 +124,37 @@ class Response
* @param mixed $data 输出数据 * @param mixed $data 输出数据
* @return $this * @return $this
*/ */
public static function data($data) public function data($data)
{ {
self::$data = $data; $this->data = $data;
return $this;
} }
/** /**
* 输出类型设置 * 输出类型设置
* @access public * @access public
* @param string $type 输出内容的格式类型 * @param string $type 输出内容的格式类型
* @return mixed * @return $this
*/ */
public static function type($type) public function type($type)
{ {
self::$type = $type; $this->type = $type;
return $this;
} }
/** /**
* 输出是否exit设置 * 输出是否exit设置
* @access public * @access public
* @param bool $exit 是否退出 * @param bool $exit 是否退出
* @return mixed * @return $this
*/ */
public static function isExit($exit = null) public function isExit($exit = null)
{ {
if (is_null($exit)) { if (is_null($exit)) {
return self::$isExit; return $this->isExit;
} }
self::$isExit = (boolean) $exit; $this->isExit = (boolean) $exit;
return $this;
} }
/** /**
@@ -186,7 +165,7 @@ class Response
* @param string $msg 提示信息 * @param string $msg 提示信息
* @return mixed * @return mixed
*/ */
public static function result($data, $code = 0, $msg = '', $type = '') public function result($data, $code = 0, $msg = '', $type = '')
{ {
$result = [ $result = [
'code' => $code, 'code' => $code,
@@ -194,7 +173,7 @@ class Response
'time' => NOW_TIME, 'time' => NOW_TIME,
'data' => $data, 'data' => $data,
]; ];
self::$type = $type; $this->type = $type;
return $result; return $result;
} }
@@ -205,7 +184,7 @@ class Response
* @param array|int $params 其它URL参数或http code * @param array|int $params 其它URL参数或http code
* @return void * @return void
*/ */
public static function redirect($url, $params = []) public function redirect($url, $params = [])
{ {
$http_response_code = 301; $http_response_code = 301;
if (is_int($params) && in_array($params, [301, 302])) { if (is_int($params) && in_array($params, [301, 302])) {
@@ -221,24 +200,22 @@ class Response
* @access public * @access public
* @param string $name 参数名 * @param string $name 参数名
* @param string $value 参数值 * @param string $value 参数值
* @return void * @return $this
*/ */
public static function header($name, $value) public function header($name, $value)
{ {
header($name . ':' . $value); header($name . ':' . $value);
return $this;
} }
/** /**
* 发送HTTP状态 * 发送HTTP状态
* @param integer $code 状态码 * @param integer $code 状态码
* @return void * @return $this
*/ */
public static function code($code) public function code($code)
{ {
if (isset(self::$statusCode[$code])) { http_response_code($code);
header('HTTP/1.1 ' . $code . ' ' . self::$statusCode[$code]); return $this;
// 确保FastCGI模式下正常
header('Status:' . $code . ' ' . self::$statusCode[$code]);
}
} }
} }

View File

@@ -92,11 +92,7 @@ abstract class Rest
*/ */
protected function response($data, $type = '', $code = 200) protected function response($data, $type = '', $code = 200)
{ {
http_response_code($code); return Response::instance()->data($data)->type($type)->code($code);
Response::data($data);
if ($type) {
Response::type($type);
}
} }
/** /**

View File

@@ -50,7 +50,7 @@ trait Jump
$result = View::instance(Config::get('template'), Config::get('view_replace_str')) $result = View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_success_tmpl'), $result); ->fetch(Config::get('dispatch_success_tmpl'), $result);
} }
Response::send($result, $type); Response::instance()->send($result, $type);
} }
/** /**
@@ -83,7 +83,7 @@ trait Jump
$result = View::instance(Config::get('template'), Config::get('view_replace_str')) $result = View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), $result); ->fetch(Config::get('dispatch_error_tmpl'), $result);
} }
Response::send($result, $type); Response::instance()->send($result, $type);
} }
/** /**
@@ -97,7 +97,7 @@ trait Jump
*/ */
public function result($data, $code = 0, $msg = '', $type = '') public function result($data, $code = 0, $msg = '', $type = '')
{ {
return Response::result($data, $code, $msg, $type); return Response::instance()->result($data, $code, $msg, $type);
} }
/** /**
@@ -109,7 +109,7 @@ trait Jump
*/ */
public function redirect($url, $params = []) public function redirect($url, $params = [])
{ {
Response::redirect($url, $params); Response::instance()->redirect($url, $params);
} }
} }

View File

@@ -70,7 +70,7 @@ class responseTest extends \PHPUnit_Framework_TestCase
{ {
Config::set('default_ajax_return', $this->default_ajax_return); Config::set('default_ajax_return', $this->default_ajax_return);
Config::set('default_return_type', $this->default_return_type); Config::set('default_return_type', $this->default_return_type);
Response::type(Config::get('default_return_type')); // 会影响其他测试 Response::instance()->type(Config::get('default_return_type')); // 会影响其他测试
} }
/** /**
@@ -83,23 +83,24 @@ class responseTest extends \PHPUnit_Framework_TestCase
$dataArr["key"] = "value"; $dataArr["key"] = "value";
//$dataArr->key = "val"; //$dataArr->key = "val";
$result = Response::send($dataArr, "", true); $response = Response::instance();
$result = $response->send($dataArr, "", true);
$this->assertArrayHasKey("key", $result); $this->assertArrayHasKey("key", $result);
$result = Response::send($dataArr, "json", true); $result = $response->send($dataArr, "json", true);
$this->assertEquals('{"key":"value"}', $result); $this->assertEquals('{"key":"value"}', $result);
$handler = "callback"; $handler = "callback";
$_GET[Config::get('var_jsonp_handler')] = $handler; $_GET[Config::get('var_jsonp_handler')] = $handler;
$result = Response::send($dataArr, "jsonp", true); $result = $response->send($dataArr, "jsonp", true);
$this->assertEquals('callback({"key":"value"});', $result); $this->assertEquals('callback({"key":"value"});', $result);
Response::transform(function () { $response->transform(function () {
return "callbackreturndata"; return "callbackreturndata";
}); });
$result = Response::send($dataArr, "", true); $result = $response->send($dataArr, "", true);
$this->assertEquals("callbackreturndata", $result); $this->assertEquals("callbackreturndata", $result);
$_GET[Config::get('var_jsonp_handler')] = ""; $_GET[Config::get('var_jsonp_handler')] = "";
} }
@@ -110,15 +111,16 @@ class responseTest extends \PHPUnit_Framework_TestCase
*/ */
public function testtransform() public function testtransform()
{ {
Response::transform(function () { $response = Response::instance();
$response->transform(function () {
return "callbackreturndata"; return "callbackreturndata";
}); });
$dataArr = []; $dataArr = [];
$result = Response::send($dataArr, "", true); $result = $response->send($dataArr, "", true);
$this->assertEquals("callbackreturndata", $result); $this->assertEquals("callbackreturndata", $result);
Response::transform(null); $response->transform(null);
} }
/** /**
@@ -128,7 +130,7 @@ class responseTest extends \PHPUnit_Framework_TestCase
public function testType() public function testType()
{ {
$type = "json"; $type = "json";
Response::type($type); Response::instance()->type($type);
} }
/** /**
@@ -138,8 +140,9 @@ class responseTest extends \PHPUnit_Framework_TestCase
public function testData() public function testData()
{ {
$data = "data"; $data = "data";
Response::data($data); $response = Response::instance();
Response::data(null); $response->data($data);
$response->data(null);
} }
/** /**
@@ -149,11 +152,12 @@ class responseTest extends \PHPUnit_Framework_TestCase
public function testIsExit() public function testIsExit()
{ {
$isExit = true; $isExit = true;
Response::isExit($isExit); $response = Response::instance();
$response->isExit($isExit);
$result = Response::isExit(); $result = $response->isExit();
$this->assertTrue($isExit, $result); $this->assertTrue($isExit, $result);
Response::isExit(false); $response->isExit(false);
} }
/** /**
@@ -166,7 +170,7 @@ class responseTest extends \PHPUnit_Framework_TestCase
$code = "1001"; $code = "1001";
$msg = "the msg"; $msg = "the msg";
$type = "json"; $type = "json";
$result = Response::result($data, $code, $msg, $type); $result = Response::instance()->result($data, $code, $msg, $type);
$this->assertEquals($code, $result["code"]); $this->assertEquals($code, $result["code"]);
$this->assertEquals($msg, $result["msg"]); $this->assertEquals($msg, $result["msg"]);