class Home extends AbstractAction { public $text; public function execute() { $this->text = "hello world"; return array('template', 'home.php'); } }
这个是渲染模板,传入 text 参数的示例。但是如果不需要渲染模板,直接输出 json 格式的数据呢?
我尝试过读源码,发现
namespace TE\Mvc\Server\Http; use TE\Mvc\Server\ResponseInterface; use TE\Mvc\View\AbstractView as View; class Response implements ResponseInterface { public function setContentType($contentType) { $this->_contentType = $contentType; return $this; } }
接着看 Response 对象的初始化:
namespace TE\Mvc\Server\Http; use TE\Mvc\Server\AbstractServer; class Server extends AbstractServer { protected function createResponse() { return new Response(); } }
如此说来,如果需要实现某个 URL 返回 JSON 格式的数据必须在 index.php 中:
// 启动Server new JSONServer(new Simple(require(ROOT . '/config/routes.php')), new InterceptorManager(require(ROOT . '/config/interceptors.php')));
然后 JSONServer 里面设置 Response::setContentType() ?
这个动静太大了,谁知道正确的姿势?!
class Home extends AbstractAction { public $text; public function execute() { $this->text = "hello world"; return array('template', 'home.php'); } }
这个是渲染模板,传入 text 参数的示例。但是如果不需要渲染模板,直接输出 json 格式的数据呢?
我尝试过读源码,发现
namespace TE\Mvc\Server\Http; use TE\Mvc\Server\ResponseInterface; use TE\Mvc\View\AbstractView as View; class Response implements ResponseInterface { public function setContentType($contentType) { $this->_contentType = $contentType; return $this; } }
接着看 Response 对象的初始化:
namespace TE\Mvc\Server\Http; use TE\Mvc\Server\AbstractServer; class Server extends AbstractServer { protected function createResponse() { return new Response(); } }
如此说来,如果需要实现某个 URL 返回 JSON 格式的数据必须在 index.php 中:
// 启动Server new JSONServer(new Simple(require(ROOT . '/config/routes.php')), new InterceptorManager(require(ROOT . '/config/interceptors.php')));
然后 JSONServer 里面设置 Response::setContentType() ?
这个动静太大了,谁知道正确的姿势?!
直接
return array('json', array('xxx' => 'xxxx'));