本文实例讲述了zend framework教程之请求对象的封装zend_controller_request方法。分享给大家供大家参考,具体如下:
概述
请求对象是在前端控制器,路由器,分发器,以及控制类间传递的简单值对象。请求对象封装了请求的模块,控制器,动作以及可选的参数,还包括其他的请求环境,如http,cli,php-gtk。
请求对象的基本实现
├── request
│ ├── abstract.php
│ ├── apache404.php
│ ├── exception.php
│ ├── http.php
│ ├── httptestcase.php
│ └── simple.php
zend_controller_request_abstract
实现了请求对象的基本方法。
<?php
abstract class zend_controller_request_abstract
{
protected $_dispatched = false;
protected $_module;
protected $_modulekey = 'module';
protected $_controller;
protected $_controllerkey = 'controller';
protected $_action;
protected $_actionkey = 'action';
protected $_params = array();
public function getmodulename()
{
if (null === $this->_module) {
$this->_module = $this->getparam($this->getmodulekey());
}
return $this->_module;
}
public function setmodulename($value)
{
$this->_module = $value;
return $this;
}
public function getcontrollername()
{
if (null === $this->_controller) {
$this->_controller = $this->getparam($this->getcontrollerkey());
}
return $this->_controller;
}
public function setcontrollername($value)
{
$this->_controller = $value;
return $this;
}
public function getactionname()
{
if (null === $this->_action) {
$this->_action = $this->getparam($this->getactionkey());
}
return $this->_action;
}
public function setactionname($value)
{
$this->_action = $value;
/**
* @see zf-3465
*/
if (null === $value) {
$this->setparam($this->getactionkey(), $value);
}
return $this;
}
public function getmodulekey()
{
return $this->_modulekey;
}
public function setmodulekey($key)
{
$this->_modulekey = (string) $key;
return $this;
}
public function getcontrollerkey()
{
return $this->_controllerkey;
}
public function setcontrollerkey($key)
{
$this->_controllerkey = (string) $key;
return $this;
}
public function getactionkey()
{
return $this->_actionkey;
}
public function setactionkey($key)
{
$this->_actionkey = (string) $key;
return $this;
}
public function getparam($key, $default = null)
{
$key = (string) $key;
if (isset($this->_params[$key])) {
return $this->_params[$key];
}
return $default;
}
public function getuserparams()
{
return $this->_params;
}
public function getuserparam($key, $default = null)
{
if (isset($this->_params[$key])) {
return $this->_params[$key];
}
return $default;
}
public function setparam($key, $value)
{
$key = (string) $key;
if ((null === $value) && isset($this->_params[$key])) {
unset($this->_params[$key]);
} elseif (null !== $value) {
$this->_params[$key] = $value;
}
return $this;
}
public function getparams()
{
return $this->_params;
}
public function setparams(array $array)
{
$this->_params = $this->_params + (array) $array;
foreach ($array as $key => $value) {
if (null === $value) {
unset($this->_params[$key]);
}
}
return $this;
}
public function clearparams()
{
$this->_params = array();
return $this;
}
public function setdispatched($flag = true)
{
$this->_dispatched = $flag ? true : false;
return $this;
}
public function isdispatched()
{
return $this->_dispatched;
}
}
zend_controller_request_http
zend_controller_request请求对象的默认实现。
<?php
require_once 'zend/controller/request/abstract.php';
require_once 'zend/uri.php';
class zend_controller_request_http extends zend_controller_request_abstract
{
const scheme_http = 'http';
const scheme_https = 'https';
protected $_paramsources = array('_get', '_post');
protected $_requesturi;
protected $_baseurl = null;
protected $_basepath = null;
protected $_pathinfo = '';
protected $_params = array();
protected $_rawbody;
protected $_aliases = array();
public function __construct($uri = null)
{
if (null !== $uri) {
if (!$uri instanceof zend_uri) {
$uri = zend_uri::factory($uri);
}
if ($uri->valid()) {
$path = $uri->getpath();
$query = $uri->getquery();
if (!empty($query)) {
$path .= '?' . $query;
}
$this->setrequesturi($path);
} else {
require_once 'zend/controller/request/exception.php';
throw new zend_controller_request_exception('invalid uri provided to constructor');
}
} else {
$this->setrequesturi();
}
}
public function __get($key)
{
switch (true) {
case isset($this->_params[$key]):
return $this->_params[$key];
case isset($_get[$key]):
return $_get[$key];
case isset($_post[$key]):
return $_post[$key];
case isset($_cookie[$key]):
return $_cookie[$key];
case ($key == 'request_uri'):
return $this->getrequesturi();
case ($key == 'path_info'):
return $this->getpathinfo();
case isset($_server[$key]):
return $_server[$key];
case isset($_env[$key]):
return $_env[$key];
default:
return null;
}
}
public function get($key)
{
return $this->__get($key);
}
public function __set($key, $value)
{
require_once 'zend/controller/request/exception.php';
throw new zend_controller_request_exception('setting values in superglobals not allowed; please use setparam()');
}
public function set($key, $value)
{
return $this->__set($key, $value);
}
public function __isset($key)
{
switch (true) {
case isset($this->_params[$key]):
return true;
case isset($_get[$key]):
return true;
case isset($_post[$key]):
return true;
case isset($_cookie[$key]):
return true;
case isset($_server[$key]):
return true;
case isset($_env[$key]):
return true;
default:
return false;
}
}
public function has($key)
{
return $this->__isset($key);
}
public function setquery($spec, $value = null)
{
if ((null === $value) && !is_array($spec)) {
require_once 'zend/controller/exception.php';
throw new zend_controller_exception('invalid value passed to setquery(); must be either array of values or key/value pair');
}
if ((null === $value) && is_array($spec)) {
foreach ($spec as $key => $value) {
$this->setquery($key, $value);
}
return $this;
}
$_get[(string) $spec] = $value;
return $this;
}
public function getquery($key = null, $default = null)
{
if (null === $key) {
return $_get;
}
return (isset($_get[$key])) ? $_get[$key] : $default;
}
public function setpost($spec, $value = null)
{
if ((null === $value) && !is_array($spec)) {
require_once 'zend/controller/exception.php';
throw new zend_controller_exception('invalid value passed to setpost(); must be either array of values or key/value pair');
}
if ((null === $value) && is_array($spec)) {
foreach ($spec as $key => $value) {
$this->setpost($key, $value);
}
return $this;
}
$_post[(string) $spec] = $value;
return $this;
}
public function getpost($key = null, $default = null)
{
if (null === $key) {
return $_post;
}
return (isset($_post[$key])) ? $_post[$key] : $default;
}
public function getcookie($key = null, $default = null)
{
if (null === $key) {
return $_cookie;
}
return (isset($_cookie[$key])) ? $_cookie[$key] : $default;
}
public function getserver($key = null, $default = null)
{
if (null === $key) {
return $_server;
}
return (isset($_server[$key])) ? $_server[$key] : $default;
}
public function getenv($key = null, $default = null)
{
if (null === $key) {
return $_env;
}
return (isset($_env[$key])) ? $_env[$key] : $default;
}
public function setrequesturi($requesturi = null)
{
if ($requesturi === null) {
if (isset($_server['http_x_rewrite_url'])) { // check this first so iis will catch
$requesturi = $_server['http_x_rewrite_url'];
} elseif (
// iis7 with url rewrite: make sure we get the unencoded url (double slash problem)
isset($_server['iis_wasurlrewritten'])
&& $_server['iis_wasurlrewritten'] == '1'
&& isset($_server['unencoded_url'])
&& $_server['unencoded_url'] != ''
) {
$requesturi = $_server['unencoded_url'];
} elseif (isset($_server['request_uri'])) {
$requesturi = $_server['request_uri'];
// http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
$schemeandhttphost = $this->getscheme() . '://' . $this->gethttphost();
if (strpos($requesturi, $schemeandhttphost) === 0) {
$requesturi = substr($requesturi, strlen($schemeandhttphost));
}
} elseif (isset($_server['orig_path_info'])) { // iis 5.0, php as cgi
$requesturi = $_server['orig_path_info'];
if (!empty($_server['query_string'])) {
$requesturi .= '?' . $_server['query_string'];
}
} else {
return $this;
}
} elseif (!is_string($requesturi)) {
return $this;
} else {
// set get items, if available
if (false !== ($pos = strpos($requesturi, '?'))) {
// get key => value pairs and set $_get
$query = substr($requesturi, $pos + 1);
parse_str($query, $vars);
$this->setquery($vars);
}
}
$this->_requesturi = $requesturi;
return $this;
}
public function getrequesturi()
{
if (empty($this->_requesturi)) {
$this->setrequesturi();
}
return $this->_requesturi;
}
public function setbaseurl($baseurl = null)
{
if ((null !== $baseurl) && !is_string($baseurl)) {
return $this;
}
if ($baseurl === null) {
$filename = (isset($_server['script_filename'])) ? basename($_server['script_filename']) : '';
if (isset($_server['script_name']) && basename($_server['script_name']) === $filename) {
$baseurl = $_server['script_name'];
} elseif (isset($_server['php_self']) && basename($_server['php_self']) === $filename) {
$baseurl = $_server['php_self'];
} elseif (isset($_server['orig_script_name']) && basename($_server['orig_script_name']) === $filename) {
$baseurl = $_server['orig_script_name']; // 1and1 shared hosting compatibility
} else {
// backtrack up the script_filename to find the portion matching
// php_self
$path = isset($_server['php_self']) ? $_server['php_self'] : '';
$file = isset($_server['script_filename']) ? $_server['script_filename'] : '';
$segs = explode('/', trim($file, '/'));
$segs = array_reverse($segs);
$index = 0;
$last = count($segs);
$baseurl = '';
do {
$seg = $segs[$index];
$baseurl = '/' . $seg . $baseurl;
++$index;
} while (($last > $index) && (false !== ($pos = strpos($path, $baseurl))) && (0 != $pos));
}
// does the baseurl have anything in common with the request_uri?
$requesturi = $this->getrequesturi();
if (0 === strpos($requesturi, $baseurl)) {
// full $baseurl matches
$this->_baseurl = $baseurl;
return $this;
}
if (0 === strpos($requesturi, dirname($baseurl))) {
// directory portion of $baseurl matches
$this->_baseurl = rtrim(dirname($baseurl), '/');
return $this;
}
$truncatedrequesturi = $requesturi;
if (($pos = strpos($requesturi, '?')) !== false) {
$truncatedrequesturi = substr($requesturi, 0, $pos);
}
$basename = basename($baseurl);
if (empty($basename) || !strpos($truncatedrequesturi, $basename)) {
// no match whatsoever; set it blank
$this->_baseurl = '';
return $this;
}
// if using mod_rewrite or isapi_rewrite strip the script filename
// out of baseurl. $pos !== 0 makes sure it is not matching a value
// from path_info or query_string
if ((strlen($requesturi) >= strlen($baseurl))
&& ((false !== ($pos = strpos($requesturi, $baseurl))) && ($pos !== 0)))
{
$baseurl = substr($requesturi, 0, $pos + strlen($baseurl));
}
}
$this->_baseurl = rtrim($baseurl, '/');
return $this;
}
public function getbaseurl($raw = false)
{
if (null === $this->_baseurl) {
$this->setbaseurl();
}
return (($raw == false) ? urldecode($this->_baseurl) : $this->_baseurl);
}
public function setbasepath($basepath = null)
{
if ($basepath === null) {
$filename = (isset($_server['script_filename']))
? basename($_server['script_filename'])
: '';
$baseurl = $this->getbaseurl();
if (empty($baseurl)) {
$this->_basepath = '';
return $this;
}
if (basename($baseurl) === $filename) {
$basepath = dirname($baseurl);
} else {
$basepath = $baseurl;
}
}
if (substr(php_os, 0, 3) === 'win') {
$basepath = str_replace('\', '/', $basepath);
}
$this->_basepath = rtrim($basepath, '/');
return $this;
}
public function getbasepath()
{
if (null === $this->_basepath) {
$this->setbasepath();
}
return $this->_basepath;
}
public function setpathinfo($pathinfo = null)
{
if ($pathinfo === null) {
$baseurl = $this->getbaseurl(); // this actually calls setbaseurl() & setrequesturi()
$baseurlraw = $this->getbaseurl(false);
$baseurlencoded = urlencode($baseurlraw);
if (null === ($requesturi = $this->getrequesturi())) {
return $this;
}
// remove the query string from request_uri
if ($pos = strpos($requesturi, '?')) {
$requesturi = substr($requesturi, 0, $pos);
}
if (!empty($baseurl) || !empty($baseurlraw)) {
if (strpos($requesturi, $baseurl) === 0) {
$pathinfo = substr($requesturi, strlen($baseurl));
} elseif (strpos($requesturi, $baseurlraw) === 0) {
$pathinfo = substr($requesturi, strlen($baseurlraw));
} elseif (strpos($requesturi, $baseurlencoded) === 0) {
$pathinfo = substr($requesturi, strlen($baseurlencoded));
} else {
$pathinfo = $requesturi;
}
} else {
$pathinfo = $requesturi;
}
}
$this->_pathinfo = (string) $pathinfo;
return $this;
}
public function getpathinfo()
{
if (empty($this->_pathinfo)) {
$this->setpathinfo();
}
return $this->_pathinfo;
}
public function setparamsources(array $paramsources = array())
{
$this->_paramsources = $paramsources;
return $this;
}
public function getparamsources()
{
return $this->_paramsources;
}
public function setparam($key, $value)
{
$key = (null !== ($alias = $this->getalias($key))) ? $alias : $key;
parent::setparam($key, $value);
return $this;
}
public function getparam($key, $default = null)
{
$keyname = (null !== ($alias = $this->getalias($key))) ? $alias : $key;
$paramsources = $this->getparamsources();
if (isset($this->_params[$keyname])) {
return $this->_params[$keyname];
} elseif (in_array('_get', $paramsources) && (isset($_get[$keyname]))) {
return $_get[$keyname];
} elseif (in_array('_post', $paramsources) && (isset($_post[$keyname]))) {
return $_post[$keyname];
}
return $default;
}
public function getparams()
{
$return = $this->_params;
$paramsources = $this->getparamsources();
if (in_array('_get', $paramsources)
&& isset($_get)
&& is_array($_get)
) {
$return += $_get;
}
if (in_array('_post', $paramsources)
&& isset($_post)
&& is_array($_post)
) {
$return += $_post;
}
return $return;
}
public function setparams(array $params)
{
foreach ($params as $key => $value) {
$this->setparam($key, $value);
}
return $this;
}
public function setalias($name, $target)
{
$this->_aliases[$name] = $target;
return $this;
}
public function getalias($name)
{
if (isset($this->_aliases[$name])) {
return $this->_aliases[$name];
}
return null;
}
public function getaliases()
{
return $this->_aliases;
}
public function getmethod()
{
return $this->getserver('request_method');
}
public function ispost()
{
if ('post' == $this->getmethod()) {
return true;
}
return false;
}
public function isget()
{
if ('get' == $this->getmethod()) {
return true;
}
return false;
}
public function isput()
{
if ('put' == $this->getmethod()) {
return true;
}
return false;
}
public function isdelete()
{
if ('delete' == $this->getmethod()) {
return true;
}
return false;
}
public function ishead()
{
if ('head' == $this->getmethod()) {
return true;
}
return false;
}
public function isoptions()
{
if ('options' == $this->getmethod()) {
return true;
}
return false;
}
public function isxmlhttprequest()
{
return ($this->getheader('x_requested_with') == 'xmlhttprequest');
}
public function isflashrequest()
{
$header = strtolower($this->getheader('user_agent'));
return (strstr($header, ' flash')) ? true : false;
}
public function issecure()
{
return ($this->getscheme() === self::scheme_https);
}
public function getrawbody()
{
if (null === $this->_rawbody) {
$body = file_get_contents('php://input');
if (strlen(trim($body)) > 0) {
$this->_rawbody = $body;
} else {
$this->_rawbody = false;
}
}
return $this->_rawbody;
}
public function getheader($header)
{
if (empty($header)) {
require_once 'zend/controller/request/exception.php';
throw new zend_controller_request_exception('an http header name is required');
}
// try to get it from the $_server array first
$temp = 'http_' . strtoupper(str_replace('-', '_', $header));
if (isset($_server[$temp])) {
return $_server[$temp];
}
// this seems to be the only way to get the authorization header on
// apache
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (isset($headers[$header])) {
return $headers[$header];
}
$header = strtolower($header);
foreach ($headers as $key => $value) {
if (strtolower($key) == $header) {
return $value;
}
}
}
return false;
}
public function getscheme()
{
return ($this->getserver('https') == 'on') ? self::scheme_https : self::scheme_http;
}
public function gethttphost()
{
$host = $this->getserver('http_host');
if (!empty($host)) {
return $host;
}
$scheme = $this->getscheme();
$name = $this->getserver('server_name');
$port = $this->getserver('server_port');
if(null === $name) {
return '';
}
elseif (($scheme == self::scheme_http && $port == 80) || ($scheme == self::scheme_https && $port == 443)) {
return $name;
} else {
return $name . ':' . $port;
}
}
public function getclientip($checkproxy = true)
{
if ($checkproxy && $this->getserver('http_client_ip') != null) {
$ip = $this->getserver('http_client_ip');
} else if ($checkproxy && $this->getserver('http_x_forwarded_for') != null) {
$ip = $this->getserver('http_x_forwarded_for');
} else {
$ip = $this->getserver('remote_addr');
}
return $ip;
}
}
从上述类的实现,不难看出,类为我们提供了很多方便的方法来获取需要的数据。例如:
模块名可通过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环境。
更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!