Zend Framework1-Zend_Controller_Request请求对象的封装

概述

请求对象是在前端控制器,路由器,分发器,以及控制类间传递的简单值对象。请求对象封装了请求的模块,控制器,动作以及可选的参数,还包括其他的请求环境,如HTTP,CLI,PHP-GTK。


请求对象的基本实现

  1. ├── Request  
  2. │   ├── Abstract.php  
  3. │   ├── Apache404.php  
  4. │   ├── Exception.php  
  5. │   ├── Http.php  
  6. │   ├── HttpTestCase.php  
  7. │   └── Simple.php  

Zend_Controller_Request_Abstract

实现了请求对象的基本方法。

  1. <?php  
  2. abstract class Zend_Controller_Request_Abstract  
  3. {  
  4.     protected $_dispatched = false;  
  5.   
  6.     protected $_module;  
  7.   
  8.     protected $_moduleKey = 'module';  
  9.   
  10.     protected $_controller;  
  11.   
  12.     protected $_controllerKey = 'controller';  
  13.   
  14.     protected $_action;  
  15.   
  16.     protected $_actionKey = 'action';  
  17.   
  18.     protected $_params = array();  
  19.   
  20.     public function getModuleName()  
  21.     {  
  22.         if (null === $this->_module) {  
  23.             $this->_module = $this->getParam($this->getModuleKey());  
  24.         }  
  25.   
  26.         return $this->_module;  
  27.     }  
  28.   
  29.     public function setModuleName($value)  
  30.     {  
  31.         $this->_module = $value;  
  32.         return $this;  
  33.     }  
  34.   
  35.     public function getControllerName()  
  36.     {  
  37.         if (null === $this->_controller) {  
  38.             $this->_controller = $this->getParam($this->getControllerKey());  
  39.         }  
  40.   
  41.         return $this->_controller;  
  42.     }  
  43.   
  44.     public function setControllerName($value)  
  45.     {  
  46.         $this->_controller = $value;  
  47.         return $this;  
  48.     }  
  49.   
  50.     public function getActionName()  
  51.     {  
  52.         if (null === $this->_action) {  
  53.             $this->_action = $this->getParam($this->getActionKey());  
  54.         }  
  55.   
  56.         return $this->_action;  
  57.     }  
  58.   
  59.     public function setActionName($value)  
  60.     {  
  61.         $this->_action = $value;  
  62.         /** 
  63.          * @see ZF-3465 
  64.          */  
  65.         if (null === $value) {  
  66.             $this->setParam($this->getActionKey(), $value);  
  67.         }  
  68.         return $this;  
  69.     }  
  70.   
  71.     public function getModuleKey()  
  72.     {  
  73.         return $this->_moduleKey;  
  74.     }  
  75.   
  76.     public function setModuleKey($key)  
  77.     {  
  78.         $this->_moduleKey = (string) $key;  
  79.         return $this;  
  80.     }  
  81.   
  82.     public function getControllerKey()  
  83.     {  
  84.         return $this->_controllerKey;  
  85.     }  
  86.   
  87.     public function setControllerKey($key)  
  88.     {  
  89.         $this->_controllerKey = (string) $key;  
  90.         return $this;  
  91.     }  
  92.   
  93.     public function getActionKey()  
  94.     {  
  95.         return $this->_actionKey;  
  96.     }  
  97.   
  98.     public function setActionKey($key)  
  99.     {  
  100.         $this->_actionKey = (string) $key;  
  101.         return $this;  
  102.     }  
  103.   
  104.     public function getParam($key$default = null)  
  105.     {  
  106.         $key = (string) $key;  
  107.         if (isset($this->_params[$key])) {  
  108.             return $this->_params[$key];  
  109.         }  
  110.   
  111.         return $default;  
  112.     }  
  113.   
  114.     public function getUserParams()  
  115.     {  
  116.         return $this->_params;  
  117.     }  
  118.   
  119.     public function getUserParam($key$default = null)  
  120.     {  
  121.         if (isset($this->_params[$key])) {  
  122.             return $this->_params[$key];  
  123.         }  
  124.   
  125.         return $default;  
  126.     }  
  127.   
  128.     public function setParam($key$value)  
  129.     {  
  130.         $key = (string) $key;  
  131.   
  132.         if ((null === $value) && isset($this->_params[$key])) {  
  133.             unset($this->_params[$key]);  
  134.         } elseif (null !== $value) {  
  135.             $this->_params[$key] = $value;  
  136.         }  
  137.   
  138.         return $this;  
  139.     }  
  140.   
  141.      public function getParams()  
  142.      {  
  143.          return $this->_params;  
  144.      }  
  145.   
  146.     public function setParams(array $array)  
  147.     {  
  148.         $this->_params = $this->_params + (array$array;  
  149.   
  150.         foreach ($array as $key => $value) {  
  151.             if (null === $value) {  
  152.                 unset($this->_params[$key]);  
  153.             }  
  154.         }  
  155.   
  156.         return $this;  
  157.     }  
  158.   
  159.     public function clearParams()  
  160.     {  
  161.         $this->_params = array();  
  162.         return $this;  
  163.     }  
  164.   
  165.     public function setDispatched($flag = true)  
  166.     {  
  167.         $this->_dispatched = $flag ? true : false;  
  168.         return $this;  
  169.     }  
  170.   
  171.     public function isDispatched()  
  172.     {  
  173.         return $this->_dispatched;  
  174.     }  
  175. }  

Zend_Controller_Request_Http

Zend_Controller_Request请求对象的默认实现。

  1. <?php  
  2. require_once 'Zend/Controller/Request/Abstract.php';  
  3. require_once 'Zend/Uri.php';  
  4. class Zend_Controller_Request_Http extends Zend_Controller_Request_Abstract  
  5. {  
  6.     const SCHEME_HTTP  = 'http';  
  7.     const SCHEME_HTTPS = 'https';  
  8.     protected $_paramSources = array('_GET''_POST');  
  9.     protected $_requestUri;  
  10.     protected $_baseUrl = null;  
  11.     protected $_basePath = null;  
  12.     protected $_pathInfo = '';  
  13.     protected $_params = array();  
  14.     protected $_rawBody;  
  15.     protected $_aliases = array();  
  16.     public function __construct($uri = null)  
  17.     {  
  18.         if (null !== $uri) {  
  19.             if (!$uri instanceof Zend_Uri) {  
  20.                 $uri = Zend_Uri::factory($uri);  
  21.             }  
  22.             if ($uri->valid()) {  
  23.                 $path  = $uri->getPath();  
  24.                 $query = $uri->getQuery();  
  25.                 if (!empty($query)) {  
  26.                     $path .= '?' . $query;  
  27.                 }  
  28.   
  29.                 $this->setRequestUri($path);  
  30.             } else {  
  31.                 require_once 'Zend/Controller/Request/Exception.php';  
  32.                 throw new Zend_Controller_Request_Exception('Invalid URI provided to constructor');  
  33.             }  
  34.         } else {  
  35.             $this->setRequestUri();  
  36.         }  
  37.     }  
  38.   
  39.     public function __get($key)  
  40.     {  
  41.         switch (true) {  
  42.             case isset($this->_params[$key]):  
  43.                 return $this->_params[$key];  
  44.             case isset($_GET[$key]):  
  45.                 return $_GET[$key];  
  46.             case isset($_POST[$key]):  
  47.                 return $_POST[$key];  
  48.             case isset($_COOKIE[$key]):  
  49.                 return $_COOKIE[$key];  
  50.             case ($key == 'REQUEST_URI'):  
  51.                 return $this->getRequestUri();  
  52.             case ($key == 'PATH_INFO'):  
  53.                 return $this->getPathInfo();  
  54.             case isset($_SERVER[$key]):  
  55.                 return $_SERVER[$key];  
  56.             case isset($_ENV[$key]):  
  57.                 return $_ENV[$key];  
  58.             default:  
  59.                 return null;  
  60.         }  
  61.     }  
  62.   
  63.     public function get($key)  
  64.     {  
  65.         return $this->__get($key);  
  66.     }  
  67.   
  68.     public function __set($key$value)  
  69.     {  
  70.         require_once 'Zend/Controller/Request/Exception.php';  
  71.         throw new Zend_Controller_Request_Exception('Setting values in superglobals not allowed; please use setParam()');  
  72.     }  
  73.     public function set($key$value)  
  74.     {  
  75.         return $this->__set($key$value);  
  76.     }  
  77.     public function __isset($key)  
  78.     {  
  79.         switch (true) {  
  80.             case isset($this->_params[$key]):  
  81.                 return true;  
  82.             case isset($_GET[$key]):  
  83.                 return true;  
  84.             case isset($_POST[$key]):  
  85.                 return true;  
  86.             case isset($_COOKIE[$key]):  
  87.                 return true;  
  88.             case isset($_SERVER[$key]):  
  89.                 return true;  
  90.             case isset($_ENV[$key]):  
  91.                 return true;  
  92.             default:  
  93.                 return false;  
  94.         }  
  95.     }  
  96.     public function has($key)  
  97.     {  
  98.         return $this->__isset($key);  
  99.     }  
  100.     public function setQuery($spec$value = null)  
  101.     {  
  102.         if ((null === $value) && !is_array($spec)) {  
  103.             require_once 'Zend/Controller/Exception.php';  
  104.             throw new Zend_Controller_Exception('Invalid value passed to setQuery(); must be either array of values or key/value pair');  
  105.         }  
  106.         if ((null === $value) && is_array($spec)) {  
  107.             foreach ($spec as $key => $value) {  
  108.                 $this->setQuery($key$value);  
  109.             }  
  110.             return $this;  
  111.         }  
  112.         $_GET[(string) $spec] = $value;  
  113.         return $this;  
  114.     }  
  115.     public function getQuery($key = null, $default = null)  
  116.     {  
  117.         if (null === $key) {  
  118.             return $_GET;  
  119.         }  
  120.   
  121.         return (isset($_GET[$key])) ? $_GET[$key] : $default;  
  122.     }  
  123.   
  124.     public function setPost($spec$value = null)  
  125.     {  
  126.         if ((null === $value) && !is_array($spec)) {  
  127.             require_once 'Zend/Controller/Exception.php';  
  128.             throw new Zend_Controller_Exception('Invalid value passed to setPost(); must be either array of values or key/value pair');  
  129.         }  
  130.         if ((null === $value) && is_array($spec)) {  
  131.             foreach ($spec as $key => $value) {  
  132.                 $this->setPost($key$value);  
  133.             }  
  134.             return $this;  
  135.         }  
  136.         $_POST[(string) $spec] = $value;  
  137.         return $this;  
  138.     }  
  139.     public function getPost($key = null, $default = null)  
  140.     {  
  141.         if (null === $key) {  
  142.             return $_POST;  
  143.         }  
  144.   
  145.         return (isset($_POST[$key])) ? $_POST[$key] : $default;  
  146.     }  
  147.     public function getCookie($key = null, $default = null)  
  148.     {  
  149.         if (null === $key) {  
  150.             return $_COOKIE;  
  151.         }  
  152.   
  153.         return (isset($_COOKIE[$key])) ? $_COOKIE[$key] : $default;  
  154.     }  
  155.     public function getServer($key = null, $default = null)  
  156.     {  
  157.         if (null === $key) {  
  158.             return $_SERVER;  
  159.         }  
  160.   
  161.         return (isset($_SERVER[$key])) ? $_SERVER[$key] : $default;  
  162.     }  
  163.     public function getEnv($key = null, $default = null)  
  164.     {  
  165.         if (null === $key) {  
  166.             return $_ENV;  
  167.         }  
  168.   
  169.         return (isset($_ENV[$key])) ? $_ENV[$key] : $default;  
  170.     }  
  171.     public function setRequestUri($requestUri = null)  
  172.     {  
  173.         if ($requestUri === null) {  
  174.             if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch  
  175.                 $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];  
  176.             } elseif (  
  177.                 // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)  
  178.                 isset($_SERVER['IIS_WasUrlRewritten'])  
  179.                 && $_SERVER['IIS_WasUrlRewritten'] == '1'  
  180.                 && isset($_SERVER['UNENCODED_URL'])  
  181.                 && $_SERVER['UNENCODED_URL'] != ''  
  182.                 ) {  
  183.                 $requestUri = $_SERVER['UNENCODED_URL'];  
  184.             } elseif (isset($_SERVER['REQUEST_URI'])) {  
  185.                 $requestUri = $_SERVER['REQUEST_URI'];  
  186.                 // Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path  
  187.                 $schemeAndHttpHost = $this->getScheme() . '://' . $this->getHttpHost();  
  188.                 if (strpos($requestUri$schemeAndHttpHost) === 0) {  
  189.                     $requestUri = substr($requestUristrlen($schemeAndHttpHost));  
  190.                 }  
  191.             } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI  
  192.                 $requestUri = $_SERVER['ORIG_PATH_INFO'];  
  193.                 if (!empty($_SERVER['QUERY_STRING'])) {  
  194.                     $requestUri .= '?' . $_SERVER['QUERY_STRING'];  
  195.                 }  
  196.             } else {  
  197.                 return $this;  
  198.             }  
  199.         } elseif (!is_string($requestUri)) {  
  200.             return $this;  
  201.         } else {  
  202.             // Set GET items, if available  
  203.             if (false !== ($pos = strpos($requestUri'?'))) {  
  204.                 // Get key => value pairs and set $_GET  
  205.                 $query = substr($requestUri$pos + 1);  
  206.                 parse_str($query$vars);  
  207.                 $this->setQuery($vars);  
  208.             }  
  209.         }  
  210.   
  211.         $this->_requestUri = $requestUri;  
  212.         return $this;  
  213.     }  
  214.     public function getRequestUri()  
  215.     {  
  216.         if (empty($this->_requestUri)) {  
  217.             $this->setRequestUri();  
  218.         }  
  219.   
  220.         return $this->_requestUri;  
  221.     }  
  222.     public function setBaseUrl($baseUrl = null)  
  223.     {  
  224.         if ((null !== $baseUrl) && !is_string($baseUrl)) {  
  225.             return $this;  
  226.         }  
  227.   
  228.         if ($baseUrl === null) {  
  229.             $filename = (isset($_SERVER['SCRIPT_FILENAME'])) ? basename($_SERVER['SCRIPT_FILENAME']) : '';  
  230.   
  231.             if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $filename) {  
  232.                 $baseUrl = $_SERVER['SCRIPT_NAME'];  
  233.             } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $filename) {  
  234.                 $baseUrl = $_SERVER['PHP_SELF'];  
  235.             } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $filename) {  
  236.                 $baseUrl = $_SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility  
  237.             } else {  
  238.                 // Backtrack up the script_filename to find the portion matching  
  239.                 // php_self  
  240.                 $path    = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '';  
  241.                 $file    = isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : '';  
  242.                 $segs    = explode('/', trim($file'/'));  
  243.                 $segs    = array_reverse($segs);  
  244.                 $index   = 0;  
  245.                 $last    = count($segs);  
  246.                 $baseUrl = '';  
  247.                 do {  
  248.                     $seg     = $segs[$index];  
  249.                     $baseUrl = '/' . $seg . $baseUrl;  
  250.                     ++$index;  
  251.                 } while (($last > $index) && (false !== ($pos = strpos($path$baseUrl))) && (0 != $pos));  
  252.             }  
  253.   
  254.             // Does the baseUrl have anything in common with the request_uri?  
  255.             $requestUri = $this->getRequestUri();  
  256.   
  257.             if (0 === strpos($requestUri$baseUrl)) {  
  258.                 // full $baseUrl matches  
  259.                 $this->_baseUrl = $baseUrl;  
  260.                 return $this;  
  261.             }  
  262.   
  263.             if (0 === strpos($requestUri, dirname($baseUrl))) {  
  264.                 // directory portion of $baseUrl matches  
  265.                 $this->_baseUrl = rtrim(dirname($baseUrl), '/');  
  266.                 return $this;  
  267.             }  
  268.   
  269.             $truncatedRequestUri = $requestUri;  
  270.             if (($pos = strpos($requestUri'?')) !== false) {  
  271.                 $truncatedRequestUri = substr($requestUri, 0, $pos);  
  272.             }  
  273.   
  274.             $basename = basename($baseUrl);  
  275.             if (empty($basename) || !strpos($truncatedRequestUri$basename)) {  
  276.                 // no match whatsoever; set it blank  
  277.                 $this->_baseUrl = '';  
  278.                 return $this;  
  279.             }  
  280.   
  281.             // If using mod_rewrite or ISAPI_Rewrite strip the script filename  
  282.             // out of baseUrl. $pos !== 0 makes sure it is not matching a value  
  283.             // from PATH_INFO or QUERY_STRING  
  284.             if ((strlen($requestUri) >= strlen($baseUrl))  
  285.                 && ((false !== ($pos = strpos($requestUri$baseUrl))) && ($pos !== 0)))  
  286.             {  
  287.                 $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));  
  288.             }  
  289.         }  
  290.   
  291.         $this->_baseUrl = rtrim($baseUrl'/');  
  292.         return $this;  
  293.     }  
  294.     public function getBaseUrl($raw = false)  
  295.     {  
  296.         if (null === $this->_baseUrl) {  
  297.             $this->setBaseUrl();  
  298.         }  
  299.   
  300.         return (($raw == false) ? urldecode($this->_baseUrl) : $this->_baseUrl);  
  301.     }  
  302.     public function setBasePath($basePath = null)  
  303.     {  
  304.         if ($basePath === null) {  
  305.             $filename = (isset($_SERVER['SCRIPT_FILENAME']))  
  306.                       ? basename($_SERVER['SCRIPT_FILENAME'])  
  307.                       : '';  
  308.   
  309.             $baseUrl = $this->getBaseUrl();  
  310.             if (empty($baseUrl)) {  
  311.                 $this->_basePath = '';  
  312.                 return $this;  
  313.             }  
  314.   
  315.             if (basename($baseUrl) === $filename) {  
  316.                 $basePath = dirname($baseUrl);  
  317.             } else {  
  318.                 $basePath = $baseUrl;  
  319.             }  
  320.         }  
  321.   
  322.         if (substr(PHP_OS, 0, 3) === 'WIN') {  
  323.             $basePath = str_replace('\\', '/', $basePath);  
  324.         }  
  325.   
  326.         $this->_basePath = rtrim($basePath'/');  
  327.         return $this;  
  328.     }  
  329.     public function getBasePath()  
  330.     {  
  331.         if (null === $this->_basePath) {  
  332.             $this->setBasePath();  
  333.         }  
  334.   
  335.         return $this->_basePath;  
  336.     }  
  337.     public function setPathInfo($pathInfo = null)  
  338.     {  
  339.         if ($pathInfo === null) {  
  340.             $baseUrl = $this->getBaseUrl(); // this actually calls setBaseUrl() & setRequestUri()  
  341.             $baseUrlRaw = $this->getBaseUrl(false);  
  342.             $baseUrlEncoded = urlencode($baseUrlRaw);  
  343.           
  344.             if (null === ($requestUri = $this->getRequestUri())) {  
  345.                 return $this;  
  346.             }  
  347.           
  348.             // Remove the query string from REQUEST_URI  
  349.             if ($pos = strpos($requestUri'?')) {  
  350.                 $requestUri = substr($requestUri, 0, $pos);  
  351.             }  
  352.               
  353.             if (!empty($baseUrl) || !empty($baseUrlRaw)) {  
  354.                 if (strpos($requestUri$baseUrl) === 0) {  
  355.                     $pathInfo = substr($requestUristrlen($baseUrl));  
  356.                 } elseif (strpos($requestUri$baseUrlRaw) === 0) {  
  357.                     $pathInfo = substr($requestUristrlen($baseUrlRaw));  
  358.                 } elseif (strpos($requestUri$baseUrlEncoded) === 0) {  
  359.                     $pathInfo = substr($requestUristrlen($baseUrlEncoded));  
  360.                 } else {  
  361.                     $pathInfo = $requestUri;  
  362.                 }  
  363.             } else {  
  364.                 $pathInfo = $requestUri;  
  365.             }  
  366.           
  367.         }  
  368.   
  369.         $this->_pathInfo = (string) $pathInfo;  
  370.         return $this;  
  371.     }  
  372.     public function getPathInfo()  
  373.     {  
  374.         if (empty($this->_pathInfo)) {  
  375.             $this->setPathInfo();  
  376.         }  
  377.   
  378.         return $this->_pathInfo;  
  379.     }  
  380.     public function setParamSources(array $paramSources = array())  
  381.     {  
  382.         $this->_paramSources = $paramSources;  
  383.         return $this;  
  384.     }  
  385.     public function getParamSources()  
  386.     {  
  387.         return $this->_paramSources;  
  388.     }  
  389.     public function setParam($key$value)  
  390.     {  
  391.         $key = (null !== ($alias = $this->getAlias($key))) ? $alias : $key;  
  392.         parent::setParam($key$value);  
  393.         return $this;  
  394.     }  
  395.     public function getParam($key$default = null)  
  396.     {  
  397.         $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key;  
  398.   
  399.         $paramSources = $this->getParamSources();  
  400.         if (isset($this->_params[$keyName])) {  
  401.             return $this->_params[$keyName];  
  402.         } elseif (in_array('_GET'$paramSources) && (isset($_GET[$keyName]))) {  
  403.             return $_GET[$keyName];  
  404.         } elseif (in_array('_POST'$paramSources) && (isset($_POST[$keyName]))) {  
  405.             return $_POST[$keyName];  
  406.         }  
  407.   
  408.         return $default;  
  409.     }  
  410.     public function getParams()  
  411.     {  
  412.         $return       = $this->_params;  
  413.         $paramSources = $this->getParamSources();  
  414.         if (in_array('_GET'$paramSources)  
  415.             && isset($_GET)  
  416.             && is_array($_GET)  
  417.         ) {  
  418.             $return += $_GET;  
  419.         }  
  420.         if (in_array('_POST'$paramSources)  
  421.             && isset($_POST)  
  422.             && is_array($_POST)  
  423.         ) {  
  424.             $return += $_POST;  
  425.         }  
  426.         return $return;  
  427.     }  
  428.     public function setParams(array $params)  
  429.     {  
  430.         foreach ($params as $key => $value) {  
  431.             $this->setParam($key$value);  
  432.         }  
  433.         return $this;  
  434.     }  
  435.     public function setAlias($name$target)  
  436.     {  
  437.         $this->_aliases[$name] = $target;  
  438.         return $this;  
  439.     }  
  440.     public function getAlias($name)  
  441.     {  
  442.         if (isset($this->_aliases[$name])) {  
  443.             return $this->_aliases[$name];  
  444.         }  
  445.   
  446.         return null;  
  447.     }  
  448.     public function getAliases()  
  449.     {  
  450.         return $this->_aliases;  
  451.     }  
  452.     public function getMethod()  
  453.     {  
  454.         return $this->getServer('REQUEST_METHOD');  
  455.     }  
  456.     public function isPost()  
  457.     {  
  458.         if ('POST' == $this->getMethod()) {  
  459.             return true;  
  460.         }  
  461.   
  462.         return false;  
  463.     }  
  464.     public function isGet()  
  465.     {  
  466.         if ('GET' == $this->getMethod()) {  
  467.             return true;  
  468.         }  
  469.   
  470.         return false;  
  471.     }  
  472.     public function isPut()  
  473.     {  
  474.         if ('PUT' == $this->getMethod()) {  
  475.             return true;  
  476.         }  
  477.   
  478.         return false;  
  479.     }  
  480.     public function isDelete()  
  481.     {  
  482.         if ('DELETE' == $this->getMethod()) {  
  483.             return true;  
  484.         }  
  485.   
  486.         return false;  
  487.     }  
  488.     public function isHead()  
  489.     {  
  490.         if ('HEAD' == $this->getMethod()) {  
  491.             return true;  
  492.         }  
  493.   
  494.         return false;  
  495.     }  
  496.     public function isOptions()  
  497.     {  
  498.         if ('OPTIONS' == $this->getMethod()) {  
  499.             return true;  
  500.         }  
  501.   
  502.         return false;  
  503.     }  
  504.     public function isXmlHttpRequest()  
  505.     {  
  506.         return ($this->getHeader('X_REQUESTED_WITH') == 'XMLHttpRequest');  
  507.     }  
  508.     public function isFlashRequest()  
  509.     {  
  510.         $header = strtolower($this->getHeader('USER_AGENT'));  
  511.         return (strstr($header' flash')) ? true : false;  
  512.     }  
  513.     public function isSecure()  
  514.     {  
  515.         return ($this->getScheme() === self::SCHEME_HTTPS);  
  516.     }  
  517.     public function getRawBody()  
  518.     {  
  519.         if (null === $this->_rawBody) {  
  520.             $body = file_get_contents('php://input');  
  521.   
  522.             if (strlen(trim($body)) > 0) {  
  523.                 $this->_rawBody = $body;  
  524.             } else {  
  525.                 $this->_rawBody = false;  
  526.             }  
  527.         }  
  528.         return $this->_rawBody;  
  529.     }  
  530.     public function getHeader($header)  
  531.     {  
  532.         if (empty($header)) {  
  533.             require_once 'Zend/Controller/Request/Exception.php';  
  534.             throw new Zend_Controller_Request_Exception('An HTTP header name is required');  
  535.         }  
  536.   
  537.         // Try to get it from the $_SERVER array first  
  538.         $temp = 'HTTP_' . strtoupper(str_replace('-''_'$header));  
  539.         if (isset($_SERVER[$temp])) {  
  540.             return $_SERVER[$temp];  
  541.         }  
  542.   
  543.         // This seems to be the only way to get the Authorization header on  
  544.         // Apache  
  545.         if (function_exists('apache_request_headers')) {  
  546.             $headers = apache_request_headers();  
  547.             if (isset($headers[$header])) {  
  548.                 return $headers[$header];  
  549.             }  
  550.             $header = strtolower($header);  
  551.             foreach ($headers as $key => $value) {  
  552.                 if (strtolower($key) == $header) {  
  553.                     return $value;  
  554.                 }  
  555.             }  
  556.         }  
  557.   
  558.         return false;  
  559.     }  
  560.     public function getScheme()  
  561.     {  
  562.         return ($this->getServer('HTTPS') == 'on') ? self::SCHEME_HTTPS : self::SCHEME_HTTP;  
  563.     }  
  564.     public function getHttpHost()  
  565.     {  
  566.         $host = $this->getServer('HTTP_HOST');  
  567.         if (!empty($host)) {  
  568.             return $host;  
  569.         }  
  570.   
  571.         $scheme = $this->getScheme();  
  572.         $name   = $this->getServer('SERVER_NAME');  
  573.         $port   = $this->getServer('SERVER_PORT');  
  574.   
  575.         if(null === $name) {  
  576.             return '';  
  577.         }  
  578.         elseif (($scheme == self::SCHEME_HTTP && $port == 80) || ($scheme == self::SCHEME_HTTPS && $port == 443)) {  
  579.             return $name;  
  580.         } else {  
  581.             return $name . ':' . $port;  
  582.         }  
  583.     }  
  584.     public function getClientIp($checkProxy = true)  
  585.     {  
  586.         if ($checkProxy && $this->getServer('HTTP_CLIENT_IP') != null) {  
  587.             $ip = $this->getServer('HTTP_CLIENT_IP');  
  588.         } else if ($checkProxy && $this->getServer('HTTP_X_FORWARDED_FOR') != null) {  
  589.             $ip = $this->getServer('HTTP_X_FORWARDED_FOR');  
  590.         } else {  
  591.             $ip = $this->getServer('REMOTE_ADDR');  
  592.         }  
  593.   
  594.         return $ip;  
  595.     }  
  596. }  


从上述类的实现,不难看出,类为我们提供了很多方便的方法来获取需要的数据。例如:


模块名可通过getModuleName()和setModuleName()访问。

控制器名可通过getControllerName()和setControllerName()访问。

控制器调用的动作名称可通过getActionName()和setActionName()访问。

可访问的参数是一个键值对的关联数组。数组可通过getParams()和 setParams()获取及设置,单个参数可以通过 getParam() 和 setParam()获取及设置。
基于请求的类型存在更多的可用方法。默认的Zend_Controller_Request_Http请求对象,拥有访问请求url、路径信息、$_GET 和 $_POST参数的方法等等。
请求对象先被传入到前端控制器。如果没有提供请求对象,它将在分发过程的开始、任何路由过程发生之前实例化。请求对象将被传递到分发链中的每个对象。
而且,请求对象在测试中是很有用的。开发人员可根据需要搭建请求环境,包括模块、控制器、动作、参数、URI等等,并且将其传入前端控制器来测试程序流向。如果与响应对象配合,可以对MVC程序进行精确巧妙的单元测试(unit testing)。

HTTP 请求
访问请求数据
Zend_Controller_Request_Http封装了对相关值的访问,如控制器和动作路由器变量的键名和值,从URL解析的附加参数。它还允许访问作为公共成员的超全局变量,管理当前的基地址(Base URL)和请求URI。超全局变量不能在请求对象中赋值,但可以通过setParam/getParam方法设定/获取用户参数。

Note: 超全局数据
通过Zend_Controller_Request_Http访问公共成员属性的超全局数据,有必要认识到一点,这些属性名(超全局数组的键)按照特定次序匹配超全局变量:1. GET,2.POST,3. COOKIE,4. SERVER,5. ENV。 
特定的超全局变量也可以选择特定的方法来访问,如$_POST['user']可以调用请求对象的getPost('user')访问,getQuery()可以获取$_GET元素,getHeader()可以获取请求消息头。

Note: GET和POST数据
需要注意:在请求对象中访问数据是没有经过任何过滤的,路由器和分发器根据任务来验证过滤数据,但在请求对象中没有任何处理。 
Note: 也获取原始 (Raw) POST 数据!
从 1.5.0 开始,也可以通过 getRawBody() 方法获取原始 post 数据。如果没有数据以那种方式提交,该方法返回 false,但 post 的全体(full boday)是个例外。 
当开发一个 RESTful MVC 程序,这个对于接受内容相当有用。 
可以在请求对象中使用setParam() 和getParam()来设置和获取用户参数。 路由器根据请求URI中的参数,利用这项功能请求对象设定参数。

Note: getParam()不只可以获取用户参数
getParam()事实上从几个资源中获取参数。根据优先级排序:通过setParam()设置的用户参数,GET 参数,最后是POST参数。 通过该方法获取数据时需要注意这点。 
如果你希望从你通过 setParam() 设置的参数中获取(参数),使用 getUserParam()。

另外,从 1.5.0 开始,可以锁定搜索哪个参数源,setParamSources() 允许指定一个空数组或者一个带有一个或多个指示哪个参数源被允许(缺省两者都被允许)的值 '_GET'或'_POST'的数组;如果想限制只访问 '_GET',那么指定 setParamSources(array('_GET')) 。

Note: Apache相关
如果使用apache的404处理器来传递请求到前端控制器,或者使用重写规则(rewrite rules)的PT标志,URI包含在$_SERVER['REDIRECT_URL'],而不是$_SERVER['REQUEST_URI']。如果使用这样的设定并获取无效的路由,应该使用Zend_Controller_Request_Apache404类代替默认的HTTP类: 
$request = new Zend_Controller_Request_Apache404();
$front->setRequest($request);
                
这个类继承了Zend_Controller_Request_Http,并简单的修改了请求URI的自动发现(autodiscovery),它可以用来作为简易替换器件(drop-in replacement)。 
基地址和子目录

Zend_Controller_Request_Http允许在子目录中使用Zend_Controller_Router_Rewrite。Zend_Controller_Request_Http试图自动的检测你的基地址,并进行相应的设置。

例如,如果将 index.php 放在web服务器的名为/projects/myapp/index.php子目录中,基地址应该被设置为/projects/myapp。计算任何路由匹配之前将先从路径中去除这个字符串。这个字串需要被加入到任何路由前面。路由 'user/:username'将匹配类似http://localhost/projects/myapp/user/martel 和http://example.com/user/martel的URL。

Note: URL检测区分大小写
基地址的自动检测是区分大小写的,因此需要确保URL与文件系统中的子目录匹配。否则将会引发异常。 
如果基地址经检测不正确,可以利用Zend_Controller_Request_Http或者Zend_Controller_Front类的setBaseUrl()方法设置自己的基路径。Zend_Controller_Front设置最容易,它将导入基地址到请求对象。定制基地址的用法举例:

/**
 * Dispatch Request with custom base URL with Zend_Controller_Front.
 */
$router     = new Zend_Controller_Router_Rewrite();
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory('./application/controllers')
           ->setRouter($router)
           ->setBaseUrl('/projects/myapp'); // set the base url!
$response   = $controller->dispatch();

            
判断请求方式


getMethod() 允许你决定用于请求当前资源的 HTTP 请求方法。另外,当询问是否一个请求的特定类型是否已经存在,有许多方法允许你获得布尔响应:

isGet()
isPost()
isPut()
isDelete()
isHead()
isOptions()
这些基本用例是来创建 RESTful MVC 架构的。


 AJAX 请求

Zend_Controller_Request_Http 有一个初步的方法用来检测AJAX请求:isXmlHttpRequest()。这个方法寻找一个带有'XMLHttpRequest' 值的HTTP请求头X-Requested-With;如果发现,就返回true。
当前,这个头用下列JS库缺省地传递:
Prototype/Scriptaculous (and libraries derived from Prototype)
Yahoo! UI Library
jQuery
MochiKit
大多数 AJAX 库允许发送定制的HTTP请求头;如果你的库没有发送这个头,简单地把它作为一个请求头添加上确保isXmlHttpRequest() 方法工作。

子类化请求对象。



请求对象是请求环境的容器。控制器链实际上只需要知道如何设置和获取控制器、动作,可选的参数以及分发的状态。默认的,请求将使用controller和action键查询自己的参数来确定控制器和动作。
需要一个请求类来与特定的环境交互以获得需要的数据时,可以扩展该基类或它的衍生类。例如HTTP环境,CLI环境,或者PHP-GTK环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值