当前位置:首页 > CMS教程 > 其它CMS > 列表

Zend Framework教程之请求对象的封装Zend_Controller_Request实例详解

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-13 15:48:43 浏览: 评论:0 

这篇文章主要介绍了Zend Framework教程之请求对象的封装Zend_Controller_Request用法,结合实例形式详细分析了请求对象封装的原理,使用方法与相关注意事项,需要的朋友可以参考下

本文实例讲述了Zend Framework教程之请求对象的封装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.   protected $_module; 
  6.   protected $_moduleKey = 'module'; 
  7.   protected $_controller; 
  8.   protected $_controllerKey = 'controller'; 
  9.   protected $_action; 
  10.   protected $_actionKey = 'action'; 
  11.   protected $_params = array(); 
  12.   public function getModuleName() 
  13.   { 
  14.     if (null === $this->_module) { 
  15.       $this->_module = $this->getParam($this->getModuleKey()); 
  16.     } 
  17.     return $this->_module; 
  18.   } 
  19.   public function setModuleName($value) 
  20.   { 
  21.     $this->_module = $value; 
  22.     return $this; 
  23.   } 
  24.   public function getControllerName() 
  25.   { 
  26.     if (null === $this->_controller) { 
  27.       $this->_controller = $this->getParam($this->getControllerKey()); 
  28.     } 
  29.     return $this->_controller; 
  30.   } 
  31.   public function setControllerName($value) 
  32.   { 
  33.     $this->_controller = $value; 
  34.     return $this; 
  35.   } 
  36.   public function getActionName() 
  37.   { 
  38.     if (null === $this->_action) { 
  39.       $this->_action = $this->getParam($this->getActionKey()); 
  40.     } 
  41.     return $this->_action; 
  42.   } 
  43.   public function setActionName($value) 
  44.   { 
  45.     $this->_action = $value; 
  46.     /** 
  47.      * @see ZF-3465 
  48.      */ 
  49.     if (null === $value) { 
  50.       $this->setParam($this->getActionKey(), $value); 
  51.     } 
  52.     return $this; 
  53.   } 
  54.   public function getModuleKey() 
  55.   { 
  56.     return $this->_moduleKey; 
  57.   } 
  58.   public function setModuleKey($key) 
  59.   { 
  60.     $this->_moduleKey = (string) $key; 
  61.     return $this; 
  62.   } 
  63.   public function getControllerKey() 
  64.   { 
  65.     return $this->_controllerKey; 
  66.   } 
  67.   public function setControllerKey($key) 
  68.   { 
  69.     $this->_controllerKey = (string) $key; 
  70.     return $this; 
  71.   } 
  72.   public function getActionKey() 
  73.   { 
  74.     return $this->_actionKey; 
  75.   } 
  76.   public function setActionKey($key) 
  77.   { 
  78.     $this->_actionKey = (string) $key; 
  79.     return $this; 
  80.   } 
  81.   public function getParam($key, $default = null) 
  82.   { 
  83.     $key = (string) $key; 
  84.     if (isset($this->_params[$key])) { 
  85.       return $this->_params[$key]; 
  86.     } 
  87.     return $default; 
  88.   } 
  89.   public function getUserParams() 
  90.   { 
  91.     return $this->_params; 
  92.   } 
  93.   public function getUserParam($key, $default = null) 
  94.   { 
  95.     if (isset($this->_params[$key])) { 
  96.       return $this->_params[$key]; 
  97.     } 
  98.     return $default; 
  99.   } 
  100.   public function setParam($key, $value) 
  101.   { 
  102.     $key = (string) $key; 
  103.     if ((null === $value) && isset($this->_params[$key])) { 
  104.       unset($this->_params[$key]); 
  105.     } elseif (null !== $value) { 
  106.       $this->_params[$key] = $value; 
  107.     } 
  108.     return $this; 
  109.   } 
  110.    public function getParams() 
  111.    { 
  112.      return $this->_params; 
  113.    } 
  114.   public function setParams(array $array) 
  115.   { 
  116.     $this->_params = $this->_params + (array) $array; 
  117.     foreach ($array as $key => $value) { 
  118.       if (null === $value) { 
  119.         unset($this->_params[$key]); 
  120.       } 
  121.     } 
  122.     return $this; 
  123.   } 
  124.   public function clearParams() 
  125.   { 
  126.     $this->_params = array(); 
  127.     return $this; 
  128.   } 
  129.   public function setDispatched($flag = true) 
  130.   { 
  131.     $this->_dispatched = $flag ? true : false; 
  132.     return $this; 
  133.   } 
  134.   public function isDispatched() 
  135.   { 
  136.     return $this->_dispatched; 
  137.   } 
  138. } 

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

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

模块名可通过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设置最容易,它将导入基地址到请求对象。定制基地址的用法举例:

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

判断请求方式

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

  1. isGet() 
  2. isPost() 
  3. isPut() 
  4. isDelete() 
  5. isHead() 
  6. isOptions() 

这些基本用例是来创建 RESTful MVC 架构的。

AJAX 请求

Zend_Controller_Request_Http 有一个初步的方法用来检测AJAX请求:isXmlHttpRequest()。这个方法寻找一个带有'XMLHttpRequest' 值的HTTP请求头X-Requested-With;如果发现,就返回true。

当前,这个头用下列JS库缺省地传递:

  1. Prototype/Scriptaculous (and libraries derived from Prototype) 
  2. Yahoo! UI Library 
  3. jQuery 
  4. MochiKit 

大多数 AJAX 库允许发送定制的HTTP请求头;如果你的库没有发送这个头,简单地把它作为一个请求头添加上确保isXmlHttpRequest() 方法工作。

子类化请求对象。

请求对象是请求环境的容器,控制器链实际上只需要知道如何设置和获取控制器、动作,可选的参数以及分发的状态,默认的,请求将使用controller和action键查询自己的参数来确定控制器和动作。

需要一个请求类来与特定的环境交互以获得需要的数据时,可以扩展该基类或它的衍生类,例如HTTP环境,CLI环境,或者PHP-GTK环境。

Tags: Framework Zend_Controller_Request

分享到: