typecho-framework 中如何在 Action 中设置成返回 JSON 格式

WBOY
发布: 2016-06-06 20:46:56
原创
1081 人浏览过

<code class="lang-PHP">class Home extends AbstractAction {

    public $text;


    public function execute() {
        $this->text = "hello world";
        return array('template', 'home.php');
    }
}
</code>
登录后复制
登录后复制

这个是渲染模板,传入 text 参数的示例。但是如果不需要渲染模板,直接输出 json 格式的数据呢?

我尝试过读源码,发现

<code class="lang-PHP">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;
    }
}
</code>
登录后复制
登录后复制

接着看 Response 对象的初始化:

<code class="lang-PHP">namespace TE\Mvc\Server\Http;

use TE\Mvc\Server\AbstractServer;
class Server extends AbstractServer
{
    protected function createResponse()
    {
        return new Response();
    }
}
</code>
登录后复制
登录后复制

如此说来,如果需要实现某个 URL 返回 JSON 格式的数据必须在 index.php 中:

<code class="lang-PHP">// 启动Server
new JSONServer(new Simple(require(ROOT . '/config/routes.php')), 
    new InterceptorManager(require(ROOT . '/config/interceptors.php')));
</code>
登录后复制
登录后复制

然后 JSONServer 里面设置 Response::setContentType() ?
这个动静太大了,谁知道正确的姿势?!

回复内容:

<code class="lang-PHP">class Home extends AbstractAction {

    public $text;


    public function execute() {
        $this->text = "hello world";
        return array('template', 'home.php');
    }
}
</code>
登录后复制
登录后复制

这个是渲染模板,传入 text 参数的示例。但是如果不需要渲染模板,直接输出 json 格式的数据呢?

我尝试过读源码,发现

<code class="lang-PHP">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;
    }
}
</code>
登录后复制
登录后复制

接着看 Response 对象的初始化:

<code class="lang-PHP">namespace TE\Mvc\Server\Http;

use TE\Mvc\Server\AbstractServer;
class Server extends AbstractServer
{
    protected function createResponse()
    {
        return new Response();
    }
}
</code>
登录后复制
登录后复制

如此说来,如果需要实现某个 URL 返回 JSON 格式的数据必须在 index.php 中:

<code class="lang-PHP">// 启动Server
new JSONServer(new Simple(require(ROOT . '/config/routes.php')), 
    new InterceptorManager(require(ROOT . '/config/interceptors.php')));
</code>
登录后复制
登录后复制

然后 JSONServer 里面设置 Response::setContentType() ?
这个动静太大了,谁知道正确的姿势?!

直接

<code class="lang-php">return array('json', array('xxx' => 'xxxx'));
</code>
登录后复制
相关标签:
php
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!