| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- <?php
- namespace RR;
- /*
- *
- *
- */
- class Response{
- private static $_instance;
- /*
- *
- */
- public $_headers = Array();
- /*
- *
- */
- public $_body = Array();
- /*
- *
- */
- public $_code = 200;
- //SINGLETON==============================================
- private function __construct(){
- }
- private static function newObj(){
- if (!isset( self::$_instance )) {
- self::$_instance = new Response();
- }
- return self::$_instance;
- }
- public function getInstance(){
- if (!isset(self::$_instance)) {
- return self::newObj();
- }
- return self::$_instance;
- }
- //=======================================================
- public static function header($key, $value){
- $istance = self::getInstance();
- $istance->_headers[$key] = $value;
- return $istance;
- }
- public static function body_prepend($body = null){
- $instance = self::getInstance();
- if (null !== $body) {
- $instance->_body = (string) $body . $instance->_body;
- return $instance;
- }
- return $instance;
- }
- public static function body($body = null){
- $instance = self::getInstance();
- if (null !== $body) {
- $instance->_body = (string) $body;
- return $instance;
- }
- return $instance;
- }
- public static function body_append($body = null){
- $instance = self::getInstance();
- if (null !== $body) {
- $instance->_body .= (string) $body;
- return $instance;
- }
- return $instance;
- }
- private function send_headers(){
- foreach ($this->_headers as $key => $value) {
- header($key .': '. $value, false);
- }
- return $this;
- }
- private function send_body(){
- echo (string) $this->_body;
- return $this;
- }
- public static function send(){
- $instance = self::getInstance();
- $instance->send_headers();
- $instance->send_body();
- return $instance;
- }
- public static function json($object, $jsonp_prefix = null){
- $instance = self::getInstance();
- $instance->body('');
- $json = json_encode($object);
- if (null !== $jsonp_prefix) {
- $instance->header('Content-Type', 'text/javascript');
- $instance->body("$jsonp_prefix($json);");
- } else {
- $instance->header('Content-Type', 'application/json');
- $instance->body($json);
- }
- return $instance;
- }
- public static function redirect($url, $code = 302){
- $instance = self::getInstance();
- $instance->_code = $code;
- $instance->header('Location', $url);
- $instance->body('');
- $instance->send();
- }
- public static function back(){
- $instance = self::getInstance();
- $instance->header('Location: ', $_SERVER['HTTP_REFERER']);
- $instance->body('');
- $instance->send();
- }
- function done(){
- die;
- }
- }
|