改进Response类 增加think\response\View类 用于渲染模板响应输出

This commit is contained in:
thinkphp
2016-05-16 18:10:46 +08:00
parent 4870d743ac
commit c7c94258d0
9 changed files with 92 additions and 143 deletions

View File

@@ -336,20 +336,6 @@ function trace($log = '[think]', $level = 'log')
} }
} }
/**
* 渲染模板输出
* @param string $template 模板文件
* @param array $vars 模板变量
* @param integer $code 状态码
* @param string $type 输出类型
* @return \think\Response
*/
function view($template = '', $vars = [], $code = 200)
{
$response = new \think\response\Html();
return $response->data($template)->render(true)->vars($vars)->code($code);
}
/** /**
* 路由注册 * 路由注册
* @param string $rule 路由规则 * @param string $rule 路由规则
@@ -379,9 +365,22 @@ function request()
* @param array $options 参数 * @param array $options 参数
* @return \think\Response * @return \think\Response
*/ */
function response($type = '', $options = []) function response($data = [], $type = '', $options = [])
{ {
return Response::create($type, $options); return new Response($data, $type, $options);
}
/**
* 渲染模板输出
* @param string $template 模板文件
* @param array $vars 模板变量
* @param integer $code 状态码
* @return \think\response\View
*/
function view($template = '', $vars = [], $code = 200)
{
$response = new \think\response\View();
return $response->data($template)->vars($vars)->code($code);
} }
/** /**

View File

@@ -13,6 +13,8 @@ namespace think;
use think\exception\HttpResponseException; use think\exception\HttpResponseException;
use think\Response; use think\Response;
use think\response\Json;
use think\response\Jsonp;
/** /**
* App 应用管理 * App 应用管理
@@ -117,8 +119,20 @@ class App
// 监听app_end // 监听app_end
APP_HOOK && Hook::listen('app_end', $data); APP_HOOK && Hook::listen('app_end', $data);
$type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type');
switch ($type) {
case 'json':
$response = new Json($data);
break;
case 'jsonp':
$response = new Jsonp($data);
break;
case 'html':
default:
$response = new Response($data, $type);
break;
}
// 自动响应输出 // 自动响应输出
return Response::create($type)->send($data); return $response->send();
} }
} }
} }

View File

@@ -19,12 +19,13 @@ class Response
protected $transform; protected $transform;
// 输出数据 // 输出数据
protected $data; protected $data;
protected $type;
// 是否exit // 是否exit
protected $isExit = false; protected $isExit = false;
// 当前的contentType // 当前的contentType
protected $contentType; protected $contentType;
// 可用的输出类型 // 可用的输出类型
protected static $contentTypes = [ protected $contentTypes = [
'json' => 'application/json', 'json' => 'application/json',
'xml' => 'text/xml', 'xml' => 'text/xml',
'html' => 'text/html', 'html' => 'text/html',
@@ -43,52 +44,18 @@ class Response
* @access public * @access public
* @param array $options 参数 * @param array $options 参数
*/ */
public function __construct($options = []) public function __construct($data = [], $type = '', $options = [])
{ {
$this->data = $data;
$this->type = strtolower($type ?: (IS_AJAX ? 'json' : 'html'));
if (isset($this->contentTypes[$this->type])) {
$this->contentType($this->contentTypes[$this->type]);
}
$this->options = array_merge($this->options, $options); $this->options = array_merge($this->options, $options);
} }
/**
* 创建一个response对象
* @access public
* @param string $type 输出类型
* @param array $options 参数
* @return \think\Response
*/
public static function create($type = '', $options = [])
{
$type = strtolower($type ?: (IS_AJAX ? 'json' : 'html'));
if (!isset(self::$instance[$type])) {
$class = '\\think\\response\\' . ucfirst($type);
$response = class_exists($class) ? new $class($options) : new static($options);
if (isset(self::$contentTypes[$type])) {
$response->contentType(self::$contentTypes[$type]);
}
self::$instance[$type] = $response;
}
return self::$instance[$type];
}
/**
* 输出类型设置
* @access public
* @param string $type 输出内容的格式类型
* @param array $options 参数
* @return $this
*/
public function type($type, $options = [])
{
$type = strtolower($type);
if (isset(self::$instance[$type])) {
return self::$instance[$type];
} else {
return self::create($type, $options);
}
}
/** /**
* 发送数据到客户端 * 发送数据到客户端
* @access public * @access public

View File

@@ -12,6 +12,7 @@
namespace think\controller; namespace think\controller;
use think\Response; use think\Response;
use think\response\Json;
abstract class Rest abstract class Rest
{ {
@@ -90,9 +91,13 @@ abstract class Rest
* @param integer $code HTTP状态 * @param integer $code HTTP状态
* @return void * @return void
*/ */
protected function response($data, $type = '', $code = 200) protected function response($data, $type = 'json', $code = 200)
{ {
return Response::create($type)->data($data)->code($code); if('json'==$type){
return new Json($data)->code($code);
}else{
return new Response($data,$type)->code($code);
}
} }
/** /**

View File

@@ -151,7 +151,7 @@ class Handle
// 获取并清空缓存 // 获取并清空缓存
$content = ob_get_clean(); $content = ob_get_clean();
$response = Response::create('html')->data($content); $response = new Response($content, 'html');
if ($exception instanceof HttpException) { if ($exception instanceof HttpException) {
$statusCode = $exception->getStatusCode(); $statusCode = $exception->getStatusCode();

View File

@@ -21,7 +21,7 @@ class Jsonp extends Response
'default_jsonp_handler' => 'jsonpReturn', 'default_jsonp_handler' => 'jsonpReturn',
'json_encode_param' => JSON_UNESCAPED_UNICODE, 'json_encode_param' => JSON_UNESCAPED_UNICODE,
]; ];
protected $contentType = 'application/json'; protected $contentType = 'application/javascript';
/** /**
* 处理数据 * 处理数据

View File

@@ -13,16 +13,15 @@ namespace think\response;
use think\Config; use think\Config;
use think\Response; use think\Response;
use think\View; use think\View as ViewTemplate;
class Html extends Response class View extends Response
{ {
// 输出参数 // 输出参数
protected $options = []; protected $options = [];
protected $vars = []; protected $vars = [];
protected $replace = []; protected $replace = [];
protected $contentType = 'text/html'; protected $contentType = 'text/html';
protected $render = false;
/** /**
* 处理数据 * 处理数据
@@ -32,26 +31,9 @@ class Html extends Response
*/ */
protected function output($data) protected function output($data)
{ {
// 返回JSON数据格式到客户端 包含状态信息 // 渲染模板输出
if ($this->render) { return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
// 渲染模板输出 ->fetch($data, $this->vars, $this->replace);
return View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch($data, $this->vars, $this->replace, [], false, false);
} else {
return $data;
}
}
/**
* 是否需要进行视图渲染
* @access protected
* @param bool $render 是否渲染
* @return $this
*/
public function render($render = true)
{
$this->render = $render;
return $this;
} }
/** /**

View File

@@ -15,8 +15,12 @@
namespace traits\controller; namespace traits\controller;
use think\Config; use think\Config;
use think\exception\HttpResponseException;
use think\Response; use think\Response;
use think\View; use think\response\Json;
use think\response\Jsonp;
use think\response\Redirect;
use think\View as ViewTemplate;
trait Jump trait Jump
{ {
@@ -46,11 +50,20 @@ trait Jump
$type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type');
if ('html' == $type) { switch ($type) {
$result = View::instance(Config::get('template'), Config::get('view_replace_str')) case 'html':
->fetch(Config::get('dispatch_success_tmpl'), $result); $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_success_tmpl'), $result);
$response = new Response($result, $type);
break;
case 'json':
$response = new Json($result);
break;
case 'jsonp':
$response = new Jsonp($result);
break;
} }
return Response::create($type)->data($result); return $response;
} }
/** /**
@@ -79,11 +92,20 @@ trait Jump
$type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type'); $type = IS_AJAX ? Config::get('default_ajax_return') : Config::get('default_return_type');
if ('html' == $type) { switch ($type) {
$result = View::instance(Config::get('template'), Config::get('view_replace_str')) case 'html':
->fetch(Config::get('dispatch_error_tmpl'), $result); $result = ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), $result);
$response = new Response($result, $type);
break;
case 'json':
$response = new Json($result);
break;
case 'jsonp':
$response = new Jsonp($result);
break;
} }
return Response::create($type)->data($result); throw new HttpResponseException($response);
} }
/** /**
@@ -97,7 +119,7 @@ trait Jump
*/ */
public function result($data, $code = 0, $msg = '', $type = '') public function result($data, $code = 0, $msg = '', $type = '')
{ {
return Response::create($type)->result($data, $code, $msg); return (new Response([], $type))->result($data, $code, $msg);
} }
/** /**
@@ -110,7 +132,7 @@ trait Jump
*/ */
public function redirect($url, $code = 301, $params = []) public function redirect($url, $code = 301, $params = [])
{ {
return Response::create('redirect')->data($url)->code($code)->params($params); return (new Redirect($url))->code($code)->params($params);
} }
} }

View File

@@ -70,7 +70,6 @@ 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::create(Config::get('default_return_type')); // 会影响其他测试
} }
/** /**
@@ -83,63 +82,24 @@ class responseTest extends \PHPUnit_Framework_TestCase
$dataArr["key"] = "value"; $dataArr["key"] = "value";
//$dataArr->key = "val"; //$dataArr->key = "val";
$response = Response::create(); $response = new \think\response\Json();
$result = $response->type('json')->send($dataArr); $result = $response->send($dataArr);
$this->assertEquals('{"key":"value"}', $result); $this->assertEquals('{"key":"value"}', $result);
$_GET['callback'] = 'callback'; $_GET['callback'] = 'callback';
$result = $response->type('jsonp', ['var_jsonp_handler' => 'callback'])->send($dataArr); $response = new \think\response\Jsonp();
$result = $response->options(['var_jsonp_handler' => 'callback'])->send($dataArr);
$this->assertEquals('callback({"key":"value"});', $result); $this->assertEquals('callback({"key":"value"});', $result);
$response = new Response();
$response->transform(function () { $response->transform(function () {
return "callbackreturndata"; return "callbackreturndata";
}); });
$result = $response->send($dataArr); $result = $response->send($dataArr);
$this->assertEquals("callbackreturndata", $result); $this->assertEquals("callbackreturndata", $result);
$_GET[Config::get('var_jsonp_handler')] = ""; $_GET[Config::get('var_jsonp_handler')] = "";
} }
/**
* @covers think\Response::transform
* @todo Implement testtransform().
*/
public function testtransform()
{
$response = Response::create();
$response->transform(function () {
return "callbackreturndata";
});
$dataArr = [];
$result = $response->send($dataArr);
$this->assertEquals("callbackreturndata", $result);
$response->transform(null);
}
/**
* @covers think\Response::type
* @todo Implement testType().
*/
public function testType()
{
$type = "json";
Response::create($type);
}
/**
* @covers think\Response::data
* @todo Implement testData().
*/
public function testData()
{
$data = "data";
$response = Response::create();
$response->data($data);
$response->data(null);
}
/** /**
* @#runInSeparateProcess * @#runInSeparateProcess
* @covers think\Response::redirect * @covers think\Response::redirect