请知悉:本文最近一次更新为 7年 前,文中内容可能已经过时。

本节对应书里的The response component。
原文翻译整理如下:

那么,这个组件可以做什么?事实上,和响应输出相关的任何事都可以做到。使用这个组件,我们可以设置headers,重定向请求,设置并发送cookies,设置内容等等。这里是一些常见的方法:

<?php
public function testRedirectAction()
{
$response = $this->getDI()->get('response');
// or you can use $this->response directly

// Redirect the user to another url
$this->view->disable();
return $response->redirect('https://www.google.com/', true);
}

重定向方法,有三个参数:地址(字符串),如果是外部重定向的话(默认布尔值为false),HTTP状态码(范围)。下面就是重定向方法代码:

<?php
/**
* Redirect by HTTP to another action or URL
*
* @param string $location
* @param boolean $externalRedirect
* @param int $statusCode
* @return PhalconHttpResponseInterface
*/
public function redirect($location, $externalRedirect, $statusCode);

另一个有用的方法是setHeader方法:

<?php
public function testSetHeaderAction()
{
$this->response->setHeader('APIKEY', 'AWQ23XX258561');
}

上面的代码示例在header里设置了APIKEY,值为 aAWQ23XX258561。
当开发API时,发送header是一种常见的方法。您可以使用该方法发送任何类型的header参数来覆盖当前的header。

内容组件相关的方法:setcontent()和setjsoncontent()。让我们看看代码示例:

<?php
public function testContentAction()
{
// First, we disable the view if there is any $this->view->disable();
// Set a plain/text or html content $this->response->setContent('I love PhalconPHP');
// OR
// Set a json content (this will return a json object)
$this->response->setJsonContent(array(
'framework' => 'PhalconPHP'
'versions' => array(
'1.3.2',
'1.3.3',
'2.0.0'
)
));
// We send the output to the client return $this->response->send();
}

当你需要发送任何JSON响应的时候,你需要使用响应组件设置header中响应类型为application/json:

<?php
$this->response->setContentType('application/json', 'UTF-8');

现在我们了解响应/请求组件的基本知识,我们可能会发现我们自己需要用日志记录不同的东西,比如错误。为此,我们需要logger组件。


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《零基础学Phalcon 5 response 组件》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌