response.class.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. class Response {
  3. public $output = '';
  4. public $body = '';
  5. public $url;
  6. private $code = 200;
  7. public $headers = array();
  8. protected $open = true;
  9. public function __construct($url){
  10. $this->url = $url;
  11. }
  12. public function __toString(){
  13. return $this->body;
  14. }
  15. public function clear(){
  16. if($this->open){
  17. $this->body = '';
  18. }
  19. return $this;
  20. }
  21. public function write($chunk){
  22. if($this->open){
  23. $this->body .= $chunk;
  24. }
  25. return $this;
  26. }
  27. public function json($json){
  28. $this->write(json_encode($json));
  29. return $this;
  30. }
  31. public function header($name,$value){
  32. if($this->open){
  33. array_push(
  34. $this->headers,
  35. array(
  36. $name,
  37. $value
  38. )
  39. );
  40. }
  41. return $this;
  42. }
  43. public function end($chunk=''){
  44. if($this->open){
  45. $this->write($chunk);
  46. $this->open = false;
  47. http_response_code($this->code);
  48. foreach($this->headers as $k => $header){
  49. header("{$header[0]}: $header[1]");
  50. }
  51. flush();
  52. }
  53. return $this;
  54. }
  55. public function code($code=null){
  56. if(is_null($code)){
  57. return $this->code;
  58. }
  59. $this->code = $code;
  60. return $this;
  61. }
  62. }
  63. ?>