欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Zend Framework教程之响应对象的封装Zend_Controller_Response实例详解

程序员文章站 2024-04-01 20:00:34
本文实例讲述了zend framework教程之响应对象的封装zend_controller_response用法。分享给大家供大家参考,具体如下: 概述 响应对象逻辑...

本文实例讲述了zend framework教程之响应对象的封装zend_controller_response用法。分享给大家供大家参考,具体如下:

概述

响应对象逻辑上是请求对象的搭档.目的在于收集消息体和/或消息头,因而可能返回大批的结果。

zend_controller_response响应对象的基本实现

├── response
│   ├── abstract.php
│   ├── cli.php
│   ├── exception.php
│   ├── http.php
│   └── httptestcase.php

zend_controller_response_abstract

abstract class zend_controller_response_abstract
{
 /**
  * body content
  * @var array
  */
 protected $_body = array();
 /**
  * exception stack
  * @var exception
  */
 protected $_exceptions = array();
 /**
  * array of headers. each header is an array with keys 'name' and 'value'
  * @var array
  */
 protected $_headers = array();
 /**
  * array of raw headers. each header is a single string, the entire header to emit
  * @var array
  */
 protected $_headersraw = array();
 /**
  * http response code to use in headers
  * @var int
  */
 protected $_httpresponsecode = 200;
 /**
  * flag; is this response a redirect?
  * @var boolean
  */
 protected $_isredirect = false;
 /**
  * whether or not to render exceptions; off by default
  * @var boolean
  */
 protected $_renderexceptions = false;
 /**
  * flag; if true, when header operations are called after headers have been
  * sent, an exception will be raised; otherwise, processing will continue
  * as normal. defaults to true.
  *
  * @see cansendheaders()
  * @var boolean
  */
 public $headerssentthrowsexception = true;
 /**
  * normalize a header name
  *
  * normalizes a header name to x-capitalized-names
  *
  * @param string $name
  * @return string
  */
 protected function _normalizeheader($name)
 {
  $filtered = str_replace(array('-', '_'), ' ', (string) $name);
  $filtered = ucwords(strtolower($filtered));
  $filtered = str_replace(' ', '-', $filtered);
  return $filtered;
 }
 /**
  * set a header
  *
  * if $replace is true, replaces any headers already defined with that
  * $name.
  *
  * @param string $name
  * @param string $value
  * @param boolean $replace
  * @return zend_controller_response_abstract
  */
 public function setheader($name, $value, $replace = false)
 {
  $this->cansendheaders(true);
  $name = $this->_normalizeheader($name);
  $value = (string) $value;
  if ($replace) {
   foreach ($this->_headers as $key => $header) {
    if ($name == $header['name']) {
     unset($this->_headers[$key]);
    }
   }
  }
  $this->_headers[] = array(
   'name' => $name,
   'value' => $value,
   'replace' => $replace
  );
  return $this;
 }
 /**
  * set redirect url
  *
  * sets location header and response code. forces replacement of any prior
  * redirects.
  *
  * @param string $url
  * @param int $code
  * @return zend_controller_response_abstract
  */
 public function setredirect($url, $code = 302)
 {
  $this->cansendheaders(true);
  $this->setheader('location', $url, true)
    ->sethttpresponsecode($code);
  return $this;
 }
 /**
  * is this a redirect?
  *
  * @return boolean
  */
 public function isredirect()
 {
  return $this->_isredirect;
 }
 /**
  * return array of headers; see {@link $_headers} for format
  *
  * @return array
  */
 public function getheaders()
 {
  return $this->_headers;
 }
 /**
  * clear headers
  *
  * @return zend_controller_response_abstract
  */
 public function clearheaders()
 {
  $this->_headers = array();
  return $this;
 }
 /**
  * clears the specified http header
  *
  * @param string $name
  * @return zend_controller_response_abstract
  */
 public function clearheader($name)
 {
  if (! count($this->_headers)) {
   return $this;
  }
  foreach ($this->_headers as $index => $header) {
   if ($name == $header['name']) {
    unset($this->_headers[$index]);
   }
  }
  return $this;
 }
 /**
  * set raw http header
  *
  * allows setting non key => value headers, such as status codes
  *
  * @param string $value
  * @return zend_controller_response_abstract
  */
 public function setrawheader($value)
 {
  $this->cansendheaders(true);
  if ('location' == substr($value, 0, 8)) {
   $this->_isredirect = true;
  }
  $this->_headersraw[] = (string) $value;
  return $this;
 }
 /**
  * retrieve all {@link setrawheader() raw http headers}
  *
  * @return array
  */
 public function getrawheaders()
 {
  return $this->_headersraw;
 }
 /**
  * clear all {@link setrawheader() raw http headers}
  *
  * @return zend_controller_response_abstract
  */
 public function clearrawheaders()
 {
  $this->_headersraw = array();
  return $this;
 }
 /**
  * clears the specified raw http header
  *
  * @param string $headerraw
  * @return zend_controller_response_abstract
  */
 public function clearrawheader($headerraw)
 {
  if (! count($this->_headersraw)) {
   return $this;
  }
  $key = array_search($headerraw, $this->_headersraw);
  if ($key !== false) {
   unset($this->_headersraw[$key]);
  }
  return $this;
 }
 /**
  * clear all headers, normal and raw
  *
  * @return zend_controller_response_abstract
  */
 public function clearallheaders()
 {
  return $this->clearheaders()
     ->clearrawheaders();
 }
 /**
  * set http response code to use with headers
  *
  * @param int $code
  * @return zend_controller_response_abstract
  */
 public function sethttpresponsecode($code)
 {
  if (!is_int($code) || (100 > $code) || (599 < $code)) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('invalid http response code');
  }
  if ((300 <= $code) && (307 >= $code)) {
   $this->_isredirect = true;
  } else {
   $this->_isredirect = false;
  }
  $this->_httpresponsecode = $code;
  return $this;
 }
 /**
  * retrieve http response code
  *
  * @return int
  */
 public function gethttpresponsecode()
 {
  return $this->_httpresponsecode;
 }
 /**
  * can we send headers?
  *
  * @param boolean $throw whether or not to throw an exception if headers have been sent; defaults to false
  * @return boolean
  * @throws zend_controller_response_exception
  */
 public function cansendheaders($throw = false)
 {
  $ok = headers_sent($file, $line);
  if ($ok && $throw && $this->headerssentthrowsexception) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('cannot send headers; headers already sent in ' . $file . ', line ' . $line);
  }
  return !$ok;
 }
 /**
  * send all headers
  *
  * sends any headers specified. if an {@link sethttpresponsecode() http response code}
  * has been specified, it is sent with the first header.
  *
  * @return zend_controller_response_abstract
  */
 public function sendheaders()
 {
  // only check if we can send headers if we have headers to send
  if (count($this->_headersraw) || count($this->_headers) || (200 != $this->_httpresponsecode)) {
   $this->cansendheaders(true);
  } elseif (200 == $this->_httpresponsecode) {
   // haven't changed the response code, and we have no headers
   return $this;
  }
  $httpcodesent = false;
  foreach ($this->_headersraw as $header) {
   if (!$httpcodesent && $this->_httpresponsecode) {
    header($header, true, $this->_httpresponsecode);
    $httpcodesent = true;
   } else {
    header($header);
   }
  }
  foreach ($this->_headers as $header) {
   if (!$httpcodesent && $this->_httpresponsecode) {
    header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpresponsecode);
    $httpcodesent = true;
   } else {
    header($header['name'] . ': ' . $header['value'], $header['replace']);
   }
  }
  if (!$httpcodesent) {
   header('http/1.1 ' . $this->_httpresponsecode);
   $httpcodesent = true;
  }
  return $this;
 }
 /**
  * set body content
  *
  * if $name is not passed, or is not a string, resets the entire body and
  * sets the 'default' key to $content.
  *
  * if $name is a string, sets the named segment in the body array to
  * $content.
  *
  * @param string $content
  * @param null|string $name
  * @return zend_controller_response_abstract
  */
 public function setbody($content, $name = null)
 {
  if ((null === $name) || !is_string($name)) {
   $this->_body = array('default' => (string) $content);
  } else {
   $this->_body[$name] = (string) $content;
  }
  return $this;
 }
 /**
  * append content to the body content
  *
  * @param string $content
  * @param null|string $name
  * @return zend_controller_response_abstract
  */
 public function appendbody($content, $name = null)
 {
  if ((null === $name) || !is_string($name)) {
   if (isset($this->_body['default'])) {
    $this->_body['default'] .= (string) $content;
   } else {
    return $this->append('default', $content);
   }
  } elseif (isset($this->_body[$name])) {
   $this->_body[$name] .= (string) $content;
  } else {
   return $this->append($name, $content);
  }
  return $this;
 }
 /**
  * clear body array
  *
  * with no arguments, clears the entire body array. given a $name, clears
  * just that named segment; if no segment matching $name exists, returns
  * false to indicate an error.
  *
  * @param string $name named segment to clear
  * @return boolean
  */
 public function clearbody($name = null)
 {
  if (null !== $name) {
   $name = (string) $name;
   if (isset($this->_body[$name])) {
    unset($this->_body[$name]);
    return true;
   }
   return false;
  }
  $this->_body = array();
  return true;
 }
 /**
  * return the body content
  *
  * if $spec is false, returns the concatenated values of the body content
  * array. if $spec is boolean true, returns the body content array. if
  * $spec is a string and matches a named segment, returns the contents of
  * that segment; otherwise, returns null.
  *
  * @param boolean $spec
  * @return string|array|null
  */
 public function getbody($spec = false)
 {
  if (false === $spec) {
   ob_start();
   $this->outputbody();
   return ob_get_clean();
  } elseif (true === $spec) {
   return $this->_body;
  } elseif (is_string($spec) && isset($this->_body[$spec])) {
   return $this->_body[$spec];
  }
  return null;
 }
 /**
  * append a named body segment to the body content array
  *
  * if segment already exists, replaces with $content and places at end of
  * array.
  *
  * @param string $name
  * @param string $content
  * @return zend_controller_response_abstract
  */
 public function append($name, $content)
 {
  if (!is_string($name)) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('invalid body segment key ("' . gettype($name) . '")');
  }
  if (isset($this->_body[$name])) {
   unset($this->_body[$name]);
  }
  $this->_body[$name] = (string) $content;
  return $this;
 }
 /**
  * prepend a named body segment to the body content array
  *
  * if segment already exists, replaces with $content and places at top of
  * array.
  *
  * @param string $name
  * @param string $content
  * @return void
  */
 public function prepend($name, $content)
 {
  if (!is_string($name)) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('invalid body segment key ("' . gettype($name) . '")');
  }
  if (isset($this->_body[$name])) {
   unset($this->_body[$name]);
  }
  $new = array($name => (string) $content);
  $this->_body = $new + $this->_body;
  return $this;
 }
 /**
  * insert a named segment into the body content array
  *
  * @param string $name
  * @param string $content
  * @param string $parent
  * @param boolean $before whether to insert the new segment before or
  * after the parent. defaults to false (after)
  * @return zend_controller_response_abstract
  */
 public function insert($name, $content, $parent = null, $before = false)
 {
  if (!is_string($name)) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('invalid body segment key ("' . gettype($name) . '")');
  }
  if ((null !== $parent) && !is_string($parent)) {
   require_once 'zend/controller/response/exception.php';
   throw new zend_controller_response_exception('invalid body segment parent key ("' . gettype($parent) . '")');
  }
  if (isset($this->_body[$name])) {
   unset($this->_body[$name]);
  }
  if ((null === $parent) || !isset($this->_body[$parent])) {
   return $this->append($name, $content);
  }
  $ins = array($name => (string) $content);
  $keys = array_keys($this->_body);
  $loc = array_search($parent, $keys);
  if (!$before) {
   // increment location if not inserting before
   ++$loc;
  }
  if (0 === $loc) {
   // if location of key is 0, we're prepending
   $this->_body = $ins + $this->_body;
  } elseif ($loc >= (count($this->_body))) {
   // if location of key is maximal, we're appending
   $this->_body = $this->_body + $ins;
  } else {
   // otherwise, insert at location specified
   $pre = array_slice($this->_body, 0, $loc);
   $post = array_slice($this->_body, $loc);
   $this->_body = $pre + $ins + $post;
  }
  return $this;
 }
 /**
  * echo the body segments
  *
  * @return void
  */
 public function outputbody()
 {
  $body = implode('', $this->_body);
  echo $body;
 }
 /**
  * register an exception with the response
  *
  * @param exception $e
  * @return zend_controller_response_abstract
  */
 public function setexception(exception $e)
 {
  $this->_exceptions[] = $e;
  return $this;
 }
 /**
  * retrieve the exception stack
  *
  * @return array
  */
 public function getexception()
 {
  return $this->_exceptions;
 }
 /**
  * has an exception been registered with the response?
  *
  * @return boolean
  */
 public function isexception()
 {
  return !empty($this->_exceptions);
 }
 /**
  * does the response object contain an exception of a given type?
  *
  * @param string $type
  * @return boolean
  */
 public function hasexceptionoftype($type)
 {
  foreach ($this->_exceptions as $e) {
   if ($e instanceof $type) {
    return true;
   }
  }
  return false;
 }
 /**
  * does the response object contain an exception with a given message?
  *
  * @param string $message
  * @return boolean
  */
 public function hasexceptionofmessage($message)
 {
  foreach ($this->_exceptions as $e) {
   if ($message == $e->getmessage()) {
    return true;
   }
  }
  return false;
 }
 /**
  * does the response object contain an exception with a given code?
  *
  * @param int $code
  * @return boolean
  */
 public function hasexceptionofcode($code)
 {
  $code = (int) $code;
  foreach ($this->_exceptions as $e) {
   if ($code == $e->getcode()) {
    return true;
   }
  }
  return false;
 }
 /**
  * retrieve all exceptions of a given type
  *
  * @param string $type
  * @return false|array
  */
 public function getexceptionbytype($type)
 {
  $exceptions = array();
  foreach ($this->_exceptions as $e) {
   if ($e instanceof $type) {
    $exceptions[] = $e;
   }
  }
  if (empty($exceptions)) {
   $exceptions = false;
  }
  return $exceptions;
 }
 /**
  * retrieve all exceptions of a given message
  *
  * @param string $message
  * @return false|array
  */
 public function getexceptionbymessage($message)
 {
  $exceptions = array();
  foreach ($this->_exceptions as $e) {
   if ($message == $e->getmessage()) {
    $exceptions[] = $e;
   }
  }
  if (empty($exceptions)) {
   $exceptions = false;
  }
  return $exceptions;
 }
 /**
  * retrieve all exceptions of a given code
  *
  * @param mixed $code
  * @return void
  */
 public function getexceptionbycode($code)
 {
  $code  = (int) $code;
  $exceptions = array();
  foreach ($this->_exceptions as $e) {
   if ($code == $e->getcode()) {
    $exceptions[] = $e;
   }
  }
  if (empty($exceptions)) {
   $exceptions = false;
  }
  return $exceptions;
 }
 /**
  * whether or not to render exceptions (off by default)
  *
  * if called with no arguments or a null argument, returns the value of the
  * flag; otherwise, sets it and returns the current value.
  *
  * @param boolean $flag optional
  * @return boolean
  */
 public function renderexceptions($flag = null)
 {
  if (null !== $flag) {
   $this->_renderexceptions = $flag ? true : false;
  }
  return $this->_renderexceptions;
 }
 /**
  * send the response, including all headers, rendering exceptions if so
  * requested.
  *
  * @return void
  */
 public function sendresponse()
 {
  $this->sendheaders();
  if ($this->isexception() && $this->renderexceptions()) {
   $exceptions = '';
   foreach ($this->getexception() as $e) {
    $exceptions .= $e->__tostring() . "\n";
   }
   echo $exceptions;
   return;
  }
  $this->outputbody();
 }
 /**
  * magic __tostring functionality
  *
  * proxies to {@link sendresponse()} and returns response value as string
  * using output buffering.
  *
  * @return string
  */
 public function __tostring()
 {
  ob_start();
  $this->sendresponse();
  return ob_get_clean();
 }
}

zend_controller_response_http

/** zend_controller_response_abstract */
require_once 'zend/controller/response/abstract.php';
/**
 * zend_controller_response_http
 *
 * http response for controllers
 *
 * @uses zend_controller_response_abstract
 * @package zend_controller
 * @subpackage response
 */
class zend_controller_response_http extends zend_controller_response_abstract
{
}

常见使用用法

如果要发送响应输出包括消息头,使用sendresponse()。

$response->sendresponse();

note: 默认地,前端控制器完成分发请求后调用sendresponse();一般地,你不需要调用它。但是,如果你想处理响应或者用它来测试你可以使用zend_controller_front::returnresponse(true)设置returnresponse 标志覆盖默认行为:

$front->returnresponse(true);
$response = $front->dispatch();
// do some more processing, such as logging...
// and then send the output:
$response->sendresponse();

在动作控制器中使用响应对象。把结果写进响应对象,而不是直接渲染输出和发送消息头:

// within an action controller action:
// set a header
$this->getresponse()
 ->setheader('content-type', 'text/html')
 ->appendbody($content);

这样做,可以在显示内容之前,将所有消息头一次发送。

note: 如果使用动作控制器的 视图集成(view integration),你不需要在相应对象中设置渲染的视图脚本,因为zend_controller_action::render() 默认完成了这些。

如果程序中发生了异常,检查响应对象的isexception() 标志,使用getexception()获取异常。此外,可以创建定制的响应对象重定向到错误页面,记录异常消息,漂亮的格式化异常消息等。

在前端控制器执行dispatch()后可以获得响应对象,或者请求前端控制器返回响应对象代替渲染输出。

// retrieve post-dispatch:
$front->dispatch();
$response = $front->getresponse();
if ($response->isexception()) {
 // log, mail, etc...
}
// or, have the front controller dispatch() process return it
$front->returnresponse(true);
$response = $front->dispatch();
// do some processing...
// finally, echo the response
$response->sendresponse();

默认地,异常消息是不显示的。可以通过调用renderexceptions()覆盖默认设置。或者启用前端控制器的throwexceptions():

$response->renderexceptions(true);
$front->dispatch($request, $response);
// or:
$front->returnresponse(true);
$response = $front->dispatch();
$response->renderexceptions();
$response->sendresponse();
// or:
$front->throwexceptions(true);
$front->dispatch();

处理消息头

如上文所述,响应对象的一项重要职责是收集和发出http响应消息头,相应地存在大量的方法:

cansendheaders() 用来判别消息头是否已发送,该方法带有一个可选的标志指示消息头已发出时是否抛出异常。可以通过设置headerssentthrowsexception 属性为false来覆盖默认设置。
setheader($name, $value, $replace = false)用来设置单独的消息头。默认的不会替换已经存在的同名消息头,但可以设置$replace 为true强制替换.
设置消息头前,该方法先检查cansendheaders()看操作是否允许,并请求抛出异常。
setredirect($url, $code = 302) 设置http定位消息头准备重定向,如果提供http状态码,重定向将会使用该状态码。
其内部调用setheader()并使$replace 标志呈打开状态确保只发送一次定位消息头。
getheaders() 返回一个消息头数组,每个元素都是一个带有'name'和'value'键的数组。
clearheaders() 清除所有注册的键值消息头。
setrawheader() 设置没有键值对的原始消息头,比如http状态消息头。
getrawheaders() 返回所有注册的原始消息头。
clearrawheaders()清除所有的原始消息头。
clearallheaders() 清除所有的消息头,包括原始消息头和键值消息头。

除了上述方法,还有获取和设置当前请求http响应码的访问器, sethttpresponsecode() 和 gethttpresponsecode().

命名片段

相应对象支持“命名片段”。允许你将消息体分割成不同的片段,并呈一定顺序排列。因此输出的是以特定次序返回的。在其内部,主体内容被存储为一个数组,大量的访问器方法可以用来指示数组内位置和名称。

举例来说,你可以使用predispatch() 钩子来向响应对象中加入页头,然后在动作控制器中加入主体内容,最后在postdispatch()钩子中加入页脚。

// assume that this plugin class is registered with the front controller
class myplugin extends zend_controller_plugin_abstract
{
 public function predispatch(zend_controller_request_abstract $request)
 {
  $response = $this->getresponse();
  $view = new zend_view();
  $view->setbasepath('../views/scripts');
  $response->prepend('header', $view->render('header.phtml'));
 }
 public function postdispatch(zend_controller_request_abstract $request)
 {
  $response = $this->getresponse();
  $view = new zend_view();
  $view->setbasepath('../views/scripts');
  $response->append('footer', $view->render('footer.phtml'));
 }
}
// a sample action controller
class mycontroller extends zend_controller_action
{
 public function fooaction()
 {
  $this->render();
 }
}

上面的例子中,调用/my/foo会使得最终响应对象中的内容呈现下面的结构:

array(
 'header' => ..., // header content
 'default' => ..., // body content from mycontroller::fooaction()
 'footer' => ... // footer content
);

渲染响应时,会按照数组中元素顺序来渲染。

大量的方法可以用来处理命名片段:

setbody() 和 appendbody() 都允许传入一个$name参数,指示一个命名片段。如果提供了这个参数,将会覆盖指定的命名片段,如果该片段不存在就创建一个。如果没有传入$name参数到setbody(),将会重置整个主体内容。如果没有传入$name参数到appendbody(),内容被附加到'default'命名片段。
prepend($name, $content) 将创建一个$name命名片段并放置在数组的开始位置。如果该片段存在,将首先移除。
append($name, $content) 将创建一个$name命名片段,并放置在数组的结尾位置。 如果该片段存在,将首先移除。
insert($name, $content, $parent = null, $before = false) 将创建一个$name命名片段。如果提供$parent参数,新的片段视$before的值决定放置在
$parent的前面或者后面。如果该片段存在,将首先移除。
clearbody($name = null) 如果$name参数提供,将删除该片段,否则删除全部。
getbody($spec = false) 如果$spec参数为一个片段名称,将可以获取到该字段。若$spec参数为false,将返回字符串格式的命名片段顺序链。如果$spec参数为true,返回主体内容数组。

在响应对象中测试异常

如上文所述,默认的,分发过程中的异常发生会在响应对象中注册。异常会注册在一个堆中,允许你抛出所有异常--程序异常,分发异常,插件异常等。如果你要检查或者记录特定的异常,你可能想要使用响应对象的异常api:

setexception(exception $e) 注册一个异常。
isexception() 判断该异常是否注册。
getexception() 返回整个异常堆。
hasexceptionoftype($type) 判断特定类的异常是否在堆中。
hasexceptionofmessage($message) 判断带有指定消息的异常是否在堆中。
hasexceptionofcode($code) 判断带有指定代码的异常是否在堆中。
getexceptionbytype($type) 获取堆中特定类的所有异常。如果没有则返回false,否则返回数组。
getexceptionbymessage($message) 获取堆中带有特定消息的所有异常。如果没有则返回false,否则返回数组。
getexceptionbycode($code) 获取堆中带有特定编码的所有异常。如果没有则返回false,否则返回数组。
renderexceptions($flag) 设置标志指示当发送响应时是否发送其中的异常。

自定义响应对象

响应对象的目的首先在于从大量的动作和插件中收集消息头和内容,然后返回到客户端;其次,响应对象也收集发生的任何异常,以处理或者返回这些异常,再或者对终端用户隐藏它们。

响应的基类是zend_controller_response_abstract,创建的任何子类必须继承这个类或它的衍生类。前面的章节中已经列出了大量可用的方法。

自定义响应对象的原因包括基于请求环境修改返回的内容的输出方式(例如:在cli和php-gtk请求中不发送消息头)增加返回存储在命名片段中内容的最终视图的功能等等。

更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。