php教程 php手册 Zend Framework教程之响应对象的封装Zend_Controller_Response实

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

Jun 06, 2016 pm 07:34 PM
framework zend 응답 물체 캡슐화 지도 시간

本文实例讲述了Zend Framework教程之响应对象的封装Zend_Controller_Response用法。分享给大家供大家参考,具体如下: 概述 响应对象逻辑上是请求对象的搭档.目的在于收集消息体和/或消息头,因而可能返回大批的结果。 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&#63;
  *
  * @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&#63;
  *
  * @return boolean
  */
 public function isException()
 {
  return !empty($this->_exceptions);
 }
 /**
  * Does the response object contain an exception of a given type&#63;
  *
  * @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&#63;
  *
  * @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&#63;
  *
  * @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 &#63; 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程序设计有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Dewu 사용법 튜토리얼 Dewu 사용법 튜토리얼 Mar 21, 2024 pm 01:40 PM

Dewu APP는 현재 매우 인기 있는 브랜드 쇼핑 소프트웨어이지만 대부분의 사용자는 Dewu APP의 기능을 사용하는 방법을 모릅니다. 다음으로 편집기는 Dewuduo를 사용자에게 제공합니다. 관심 있는 사용자는 와서 살펴볼 수 있습니다! Dewu 이용방법 튜토리얼 [2024-03-20] Dewu 할부구매 이용방법 [2024-03-20] Dewu 쿠폰 받는 방법 [2024-03-20] Dewu 매뉴얼 고객센터 찾는 방법 [2024-03- 20] 듀우 픽업 코드 확인 방법 [2024-03-20] 듀우 구매처 찾기 [2024-03-20] 듀우 VIP 개설 방법 [2024-03-20] 듀우 반품, 교환 신청 방법

WeChat에서 결제 소리를 끄는 방법에 대한 튜토리얼 WeChat에서 결제 소리를 끄는 방법에 대한 튜토리얼 Mar 26, 2024 am 08:30 AM

1. 먼저 위챗을 엽니다. 2. 오른쪽 상단의 [+]를 클릭하세요. 3. QR코드를 클릭하시면 결제가 진행됩니다. 4. 오른쪽 상단에 있는 세 개의 작은 점을 클릭하세요. 5. 결제도착 음성알림을 클릭하시면 종료됩니다.

photoshopcs5는 어떤 소프트웨어인가요? -photoshopcs5 사용법 튜토리얼 photoshopcs5는 어떤 소프트웨어인가요? -photoshopcs5 사용법 튜토리얼 Mar 19, 2024 am 09:04 AM

PhotoshopCS는 Photoshop Creative Suite의 약자로 Adobe에서 제작한 소프트웨어입니다. 그래픽 디자인 및 이미지 처리에 널리 사용됩니다. PS를 처음 배우는 사용자로서 오늘은 photoshopcs5가 무엇인지, photoshopcs5를 사용하는 방법에 대해 설명하겠습니다. . 1. Photoshop CS5는 어떤 소프트웨어입니까? Adobe Photoshop CS5 Extended는 영화, 비디오 및 멀티미디어 분야의 전문가, 3D 및 애니메이션을 사용하는 그래픽 및 웹 디자이너, 엔지니어링 및 과학 분야의 전문가에게 이상적입니다. 3D 이미지를 렌더링하고 이를 2D 합성 이미지로 병합합니다. 쉽게 비디오 편집

여름에는 꼭 무지개를 찍어보세요 여름에는 꼭 무지개를 찍어보세요 Jul 21, 2024 pm 05:16 PM

여름에 비가 내린 후에는 아름답고 마법 같은 특별한 날씨 장면인 무지개를 자주 볼 수 있습니다. 이 역시 사진에서 볼 수 있는 보기 드문 장면으로, 매우 포토제닉하다. 무지개가 나타나는 데에는 몇 가지 조건이 있습니다. 첫째, 공기 중에 충분한 물방울이 있고, 둘째, 태양이 낮은 각도로 빛납니다. 따라서 비가 그친 후 오후에 무지개를 보는 것이 가장 쉽습니다. 그러나 무지개의 형성은 날씨, 빛, 기타 조건의 영향을 크게 받기 때문에 일반적으로 짧은 시간 동안만 지속되며, 가장 잘 볼 수 있고 촬영할 수 있는 시간은 더욱 짧습니다. 그러면 무지개를 만났을 때 어떻게 제대로 기록하고 고품질로 사진을 찍을 수 있습니까? 1. 무지개를 찾아보세요. 위에서 언급한 조건 외에도 무지개는 대개 햇빛 방향으로 나타납니다. 즉, 태양이 서쪽에서 동쪽으로 빛날 경우 무지개가 동쪽에서 나타날 확률이 높습니다.

전문가가 가르쳐드립니다! Huawei 휴대폰에서 긴 사진을 자르는 올바른 방법 전문가가 가르쳐드립니다! Huawei 휴대폰에서 긴 사진을 자르는 올바른 방법 Mar 22, 2024 pm 12:21 PM

스마트폰의 지속적인 발전과 함께 휴대폰의 기능은 점점 더 강력해졌고, 그 중 장사진 촬영 기능은 많은 사용자들이 일상생활에서 사용하는 중요한 기능 중 하나로 자리 잡았다. 긴 스크린샷은 사용자가 쉽게 보고 공유할 수 있도록 긴 웹페이지, 대화 기록, 사진을 한 번에 저장하는 데 도움이 됩니다. 많은 휴대폰 브랜드 중에서 Huawei 휴대폰은 사용자들로부터 높은 평가를 받는 브랜드 중 하나이며, 긴 사진을 자르는 기능도 높은 평가를 받고 있습니다. 이 기사에서는 Huawei 휴대폰으로 장사진을 찍는 올바른 방법과 Huawei 휴대폰을 더 잘 활용하는 데 도움이 되는 몇 가지 전문가 팁을 소개합니다.

PHP 튜토리얼: int 유형을 문자열로 변환하는 방법 PHP 튜토리얼: int 유형을 문자열로 변환하는 방법 Mar 27, 2024 pm 06:03 PM

PHP 튜토리얼: Int 유형을 문자열로 변환하는 방법 PHP에서는 정수 데이터를 문자열로 변환하는 것이 일반적인 작업입니다. 이 튜토리얼에서는 특정 코드 예제를 제공하면서 PHP의 내장 함수를 사용하여 int 유형을 문자열로 변환하는 방법을 소개합니다. 캐스트 사용: PHP에서는 캐스트를 사용하여 정수 데이터를 문자열로 변환할 수 있습니다. 이 방법은 매우 간단합니다. 정수 데이터 앞에 (문자열)을 추가하면 문자열로 변환됩니다. 아래는 간단한 샘플 코드입니다.

TrendForce: Nvidia의 Blackwell 플랫폼 제품으로 TSMC의 CoWoS 생산 능력이 올해 150% 증가합니다. TrendForce: Nvidia의 Blackwell 플랫폼 제품으로 TSMC의 CoWoS 생산 능력이 올해 150% 증가합니다. Apr 17, 2024 pm 08:00 PM

4월 17일 이 사이트의 뉴스에 따르면 TrendForce는 최근 Nvidia의 새로운 Blackwell 플랫폼 제품에 대한 수요가 강세를 보이고 있으며, 이로 인해 TSMC의 전체 CoWoS 패키징 생산 능력이 2024년에 150% 이상 증가할 것으로 예상된다는 보고서를 발표했습니다. NVIDIA Blackwell의 새로운 플랫폼 제품에는 B 시리즈 GPU와 NVIDIA 자체 GraceArm CPU를 통합한 GB200 가속기 카드가 포함됩니다. TrendForce는 현재 공급망이 GB200에 대해 매우 낙관적이며, 출하량이 2025년에 100만 개를 초과할 것으로 예상되며 이는 Nvidia 고급 GPU의 40~50%를 차지할 것으로 확인했습니다. 엔비디아는 하반기에 GB200, B100 등의 제품을 출시할 계획이지만, 업스트림 웨이퍼 패키징에는 더욱 복잡한 제품을 채택해야 합니다.

MySQL 쿼리 결과 배열을 객체로 변환하는 방법은 무엇입니까? MySQL 쿼리 결과 배열을 객체로 변환하는 방법은 무엇입니까? Apr 29, 2024 pm 01:09 PM

MySQL 쿼리 결과 배열을 객체로 변환하는 방법은 다음과 같습니다. 빈 객체 배열을 만듭니다. 결과 배열을 반복하고 각 행에 대해 새 개체를 만듭니다. foreach 루프를 사용하여 각 행의 키-값 쌍을 새 개체의 해당 속성에 할당합니다. 개체 배열에 새 개체를 추가합니다. 데이터베이스 연결을 닫습니다.

See all articles