如何自定义HttpCode?

我发现好多异常都是httpcode返回200,返回结果里的ret则返回了错误码;那如何能直接自定义httpcode呢?
已邀请:

dogstar - PhalApi创始人

赞同来自: lz0808

状态响应码可以在PhalApi_Response 找到参考。如果需要设置头部信息可以参考 https://www.phalapi.net/wikis/1-14.html" rel="nofollow" target="_blank">1.14 统一返回的格式

由于PhalApi统一默认返回200,如要改动,可以重载PhalApi_Response,然后重新注册DI()->response。

社区是大家参加交流的地方,若未能及时回复,还请见谅。
 

dogstar - PhalApi创始人

赞同来自: lz0808

具体的实现如下。 

1、新增一个类,继承PhalApi_Response,然后重载结果输出output()方法。
// $ vim ./Demo/Common/Response.php
<?php

class Common_Response extends PhalApi_Response_Json {

public function output() {
$http = array (
100 => "HTTP/1.1 100 Continue",
101 => "HTTP/1.1 101 Switching Protocols",
200 => "HTTP/1.1 200 OK",
201 => "HTTP/1.1 201 Created",
202 => "HTTP/1.1 202 Accepted",
203 => "HTTP/1.1 203 Non-Authoritative Information",
204 => "HTTP/1.1 204 No Content",
205 => "HTTP/1.1 205 Reset Content",
206 => "HTTP/1.1 206 Partial Content",
300 => "HTTP/1.1 300 Multiple Choices",
301 => "HTTP/1.1 301 Moved Permanently",
302 => "HTTP/1.1 302 Found",
303 => "HTTP/1.1 303 See Other",
304 => "HTTP/1.1 304 Not Modified",
305 => "HTTP/1.1 305 Use Proxy",
307 => "HTTP/1.1 307 Temporary Redirect",
400 => "HTTP/1.1 400 Bad Request",
401 => "HTTP/1.1 401 Unauthorized",
402 => "HTTP/1.1 402 Payment Required",
403 => "HTTP/1.1 403 Forbidden",
404 => "HTTP/1.1 404 Not Found",
405 => "HTTP/1.1 405 Method Not Allowed",
406 => "HTTP/1.1 406 Not Acceptable",
407 => "HTTP/1.1 407 Proxy Authentication Required",
408 => "HTTP/1.1 408 Request Time-out",
409 => "HTTP/1.1 409 Conflict",
410 => "HTTP/1.1 410 Gone",
411 => "HTTP/1.1 411 Length Required",
412 => "HTTP/1.1 412 Precondition Failed",
413 => "HTTP/1.1 413 Request Entity Too Large",
414 => "HTTP/1.1 414 Request-URI Too Large",
415 => "HTTP/1.1 415 Unsupported Media Type",
416 => "HTTP/1.1 416 Requested range not satisfiable",
417 => "HTTP/1.1 417 Expectation Failed",
500 => "HTTP/1.1 500 Internal Server Error",
501 => "HTTP/1.1 501 Not Implemented",
502 => "HTTP/1.1 502 Bad Gateway",
503 => "HTTP/1.1 503 Service Unavailable",
504 => "HTTP/1.1 504 Gateway Time-out"
);

if (isset($http[$this->ret])) {
header($http[$this->ret]);
}

parent::output();
}
}

2、在入口文件,重新注册DI()->response,如:
// $ vim ./Public/demo/index.php

DI()->response = 'Common_Response';

/** ---------------- 响应接口请求 ---------------- **/

3、在Api接口层,抛出对应的异常时,便可以自定义http code了,如: 
// $ vim ./Demo/Api/Default.php
class Api_Default extends PhalApi_Api {

public function index() {
throw new PhalApi_Exception_BadRequest( '无访问权限', 3);
}
}

上面异常,最终看到的效果如下: 

20170701112128.jpg


 

lz0808

赞同来自:

这都一个星期了,也没个人回复啊,这社区,简直。。。。。。。。

lz0808

赞同来自:

太感谢了~万分感谢~

dogstar - PhalApi创始人

赞同来自:

不用客气,反而我们要感谢@lz808 同学提了一个这么好的问题。最新版 v1.4.1 版本已默认支持这种自定义HttpCode,只需要改动一行即可。

更新到 v1.4.1 版本后,修改:
// Public/demo/index.php
// $rs->output();
$rs->adjustHttpStatus()->output();
文档请见:https://www.phalapi.net/wikis/1-14.html" rel="nofollow" target="_blank">将ret状态码转换成相应的Http状态码输出

要回复问题请先登录注册