返回响应(Returning Responses)

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

  1. <?php
  2.  
  3. // Getting a response instance
  4. $response = new \Phalcon\Http\Response();
  5.  
  6. // Set status code
  7. $response->setStatusCode(404, "Not Found");
  8.  
  9. // Set the content of the response
  10. $response->setContent("Sorry, the page doesn't exist");
  11.  
  12. // Send response to the client
  13. $response->send();

如果您使用的是完整的 MVC 应用,则不需要手动创建响应。但是,如果您需要直接从控制器的操作返回响应,请按照下面的示例:

  1. <?php
  2.  
  3. class FeedController extends Phalcon\Mvc\Controller
  4. {
  5. public function getAction()
  6. {
  7. // Getting a response instance
  8. $response = new \Phalcon\Http\Response();
  9.  
  10. $feed = // ... Load here the feed
  11.  
  12. // Set the content of the response
  13. $response->setContent($feed->asString());
  14.  
  15. // Return the response
  16. return $response;
  17. }
  18. }

使用头部信息(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:

  1. <?php
  2.  
  3. // Setting a header by its name
  4. $response->setHeader("Content-Type", "application/pdf");
  5. $response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');
  6.  
  7. // Setting a raw header
  8. $response->setRawHeader("HTTP/1.1 200 OK");

A Phalcon\Http\Response\Headers bag internally manages headers. This classretrieves the headers before sending it to client:

  1. <?php
  2.  
  3. // Get the headers bag
  4. $headers = $response->getHeaders();
  5.  
  6. // Get a header by its name
  7. $contentType = $response->getHeaders()->get("Content-Type");

重定向(Making Redirections)

可以通过 Phalcon\Http\Response 来执行HTTP重定向:

  1. <?php
  2.  
  3. // Redirect to the default URI
  4. $response->redirect();
  5.  
  6. // Redirect to the local base URI
  7. $response->redirect("posts/index");
  8.  
  9. // Redirect to an external URL
  10. $response->redirect("http://en.wikipedia.org", true);
  11.  
  12. // Redirect specifying the HTTP status code
  13. $response->redirect("http://www.example.com/new-location", true, 301);
  14.  
  15. // Send response to the client
  16. $response->send();

All internal URIs are generated using the ‘url’ service (by default Phalcon\Mvc\Url). This example demonstrateshow you can redirect using a route you have defined in your application:

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

  1. <?php
  2.  
  3. // Redirect based on a named route
  4. return $response->redirect(
  5. array(
  6. "for" => "index-lang",
  7. "lang" => "jp",
  8. "controller" => "index"
  9. )
  10. );

Note that a redirection doesn’t disable the view component, so if there is a view associated with the current action itwill 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 traffic is using HTTP Cache.Most modern browsers support HTTP caching and is one of the reasons why 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 storedin the browser cache. Until this date expires no new content will be requested from the server:

  1. <?php
  2.  
  3. $expireDate = new DateTime();
  4. $expireDate->modify('+2 months');
  5.  
  6. $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:

  1. <?php
  2.  
  3. $expireDate = new DateTime();
  4. $expireDate->modify('-10 minutes');
  5.  
  6. $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 tomake 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 browserhow long it must keep the page in its cache:

  1. <?php
  2.  
  3. // Starting from now, cache the page for one day
  4. $response->setHeader('Cache-Control', 'max-age=86400');

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

  1. <?php
  2.  
  3. // Never cache the served page
  4. $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:

  1. <?php
  2.  
  3. // Calculate the E-Tag based on the modification time of the latest news
  4. $recentDate = News::maximum(array('column' => 'created_at'));
  5. $eTag = md5($recentDate);
  6.  
  7. // Send an E-Tag header
  8. $response->setHeader('E-Tag', $eTag);

原文: http://www.myleftstudio.com/reference/response.html