文档
Welcome! 安装(Installation) 示例列表(List of examples) 依赖注入与服务定位器(Dependency Injection/Service Location) MVC 架构(The MVC Architecture) 使用控制器(Using Controllers) 使用模型(Working with Models) 模型元数据(Models Meta-Data) 事务管理(Model Transactions) Phalcon 查询语言(Phalcon Query Language (PHQL)) 缓存对象关系映射(Caching in the ORM) 对象文档映射 ODM (Object-Document Mapper) 使用视图(Using Views) 视图助手(View Helpers) 资源文件管理(Assets Management) Volt 模版引擎(Volt: Template Engine) MVC 应用(MVC Applications) 路由(Routing) 调度控制器(Dispatching Controllers) 微应用(Micro Applications) 使用命名空间(Working with Namespaces) 事件管理器(Events Manager) 请求环境 (Request Environment) 返回响应(Returning Responses) Cookie 管理(Cookies Management) 生成 URL 和 路径(Generating URLs and Paths) 闪存消息(Flashing Messages) 使用 Session 存储数据(Storing data in Session) 过滤与清理(Filtering and Sanitizing) 上下文编码(Contextual Escaping) 验证(Validation) 表单(Forms) 读取配置(Reading Configurations) 分页(Pagination) 使用缓存提高性能(Improving Performance with Cache) 安全(Security) 加密/解密( Encryption/Decryption ) 访问控制列表 ACL(Access Control Lists ACL) 多语言支持(Multi-lingual Support) 通用类加载器 ( Universal Class Loader ) 日志记录(Logging) 注释解析器(Annotations Parser) 命令行应用(Command Line Applications) 队列(Queueing) 数据库抽象层(Database Abstraction Layer) 国际化(Internationalization) 数据库迁移(Database Migrations) 调试应用程序(Debugging Applications) Phalcon 开发工具(Phalcon Developer Tools) 提高性能:下一步该做什么?(Increasing Performance: What's next?) 单元测试(Unit testing) 授权(License)
教程

发布于 2015-08-21 15:16:41 | 256 次阅读 | 评论: 0 | 来源: 网络整理

返回响应(Returning Responses)

Part of the HTTP cycle is returning responses to clients. PhalconHttpResponse is the Phalcon component designed to achieve this task. HTTP responses are usually composed by headers and body. The following is an example of basic usage:

<?php

use PhalconHttpResponse;

// Getting a response instance
$response = new Response();

// Set status code
$response->setStatusCode(404, "Not Found");

// Set the content of the response
$response->setContent("Sorry, the page doesn't exist");

// Send response to the client
$response->send();

If you are using the full MVC stack there is no need to create responses manually. However, if you need to return a response directly from a controller’s action follow this example:

<?php

use PhalconHttpResponse;
use PhalconMvcController;

class FeedController extends Controller
{

    public function getAction()
    {
        // Getting a response instance
        $response = new Response();

        $feed     = // .. load here the feed

        // Set the content of the response
        $response->setContent($feed->asString());

        // Return the response
        return $response;
    }

}

使用头部信息(Working with Headers)

Headers are an important part of the HTTP response. It contains useful information about the response state like the HTTP status, type of response and much more.

You can set headers in the following way:

<?php

// Setting a header by it's name
$response->setHeader("Content-Type", "application/pdf");
$response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');

// Setting a raw header
$response->setRawHeader("HTTP/1.1 200 OK");

A PhalconHttpResponseHeaders bag internally manages headers. This class retrieves the headers before sending it to client:

<?php

// Get the headers bag
$headers = $response->getHeaders();

// Get a header by its name
$contentType = $response->getHeaders()->get("Content-Type");

重定向(Making Redirections)

With PhalconHttpResponse you can also execute HTTP redirections:

可以通过 PhalconHttpResponse 来执行HTTP重定向:

<?php

// Redirect to the default URI
$response->redirect();

// Redirect to the local base URI
$response->redirect("posts/index");

// Redirect to an external URL
$response->redirect("http://en.wikipedia.org", true);

// Redirect specifyng the HTTP status code
$response->redirect("http://www.example.com/new-location", true, 301);

All internal URIs are generated using the ‘url’ service (by default PhalconMvcUrl). This example demonstrates how you can redirect using a route you have defined in your application:

所有内部 URIs 都是通过 ‘url’ 来生成的( 默认是 PhalconMvcUrl )。下面的例子演示如何通过一个应用内预先定义好的路由来重定向。

<?php

// Redirect based on a named route
return $response->redirect(array(
    "for"        => "index-lang",
    "lang"       => "jp",
    "controller" => "index"
));

Note that a redirection doesn’t disable the view component, so if there is a view associated with the current action it will be executed anyway. You can disable the view from a controller by executing $this->view->disable();

值得注意的时候重定向并不禁用view组件,所以如果当前的action存在一个关联的view的话,将会继续执行它。在控制器中可以通过 $this->view->disable() 来禁用view。

HTTP 缓存(HTTP Cache)

One of the easiest ways to improve the performance in your applications and reduce the server traffic is using HTTP Cache. Most modern browsers support HTTP caching. HTTP Cache is one of the reasons many websites are currently fast.

HTTP Cache can be altered in the following header values sent by the application when serving a page for the first time:

  • Expires: With this header the application can set a date in the future or the past telling the browser when the page must expire.
  • Cache-Control: This header allows to specify how much time a page should be considered fresh in the browser.
  • Last-Modified: This header tells the browser which was the last time the site was updated avoiding page re-loads
  • ETag: An etag is a unique identifier that must be created including the modification timestamp of the current page

设置过期时间(Setting an Expiration Time)

The expiration date is one of the easiest and most effective ways to cache a page in the client (browser). Starting from the current date we add the amount of time the page will be stored in the browser cache. Until this date expires no new content will be requested from the server:

<?php

$expireDate = new DateTime();
$expireDate->modify('+2 months');

$response->setExpires($expireDate);

The Response component automatically shows the date in GMT timezone as expected in an Expires header.

If we set this value to a date in the past the browser will always refresh the requested page:

<?php

$expireDate = new DateTime();
$expireDate->modify('-10 minutes');

$response->setExpires($expireDate);

Browsers rely on the client’s clock to assess if this date has passed or not. The client clock can be modified to make pages expire and this may represent a limitation for this cache mechanism.

Cache-Control

This header provides a safer way to cache the pages served. We simply must specify a time in seconds telling the browser how long it must keep the page in its cache:

<?php

// Starting from now, cache the page for one day
$response->setHeader('Cache-Control', 'max-age=86400');

The opposite effect (avoid page caching) is achieved in this way:

<?php

// Never cache the served page
$response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');

E-Tag

An “entity-tag” or “E-tag” is a unique identifier that helps the browser realize if the page has changed or not between two requests. The identifier must be calculated taking into account that this must change if the previously served content has changed:

<?php

// Calculate the E-Tag based on the modification time of the latest news
$recentDate = News::maximum(array('column' => 'created_at'));
$eTag       = md5($recentDate);

// Send an E-Tag header
$response->setHeader('E-Tag', $eTag);
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务