Part of the HTTP cycle is returning responses to clients. Phalcon\Http\Response 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:
<?phpusePhalcon\Http\Response;// Responseインスタンスの取得$response=newResponse();// ステータスコードの設定$response->setStatusCode(404,'Not Found');// レスポンスの内容の設定$response->setContent("Sorry, the page doesn't exist");// クライアントにレスポンスを送信$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// Redirect to the default URI$response->redirect();// Redirect to the local base URI$response->redirect('posts/index');// Redirect to an external URL$response->redirect('https://en.wikipedia.org',true);// Redirect specifying the HTTP status code$response->redirect('https://www.example.com/new-location',true,301);
All internal URIs are generated using the service (by default [Phalcon\Url](api/Phalcon_Url)). This example demonstrates how you can redirect using a route you have defined in your application:
Even if there is a view associated with the current action, it will not be rendered since redirect disables the view.
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:
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:
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$mostRecentDate=News::maximum(['column'=>'created_at',]);$eTag=md5($mostRecentDate);// Send an E-Tag header$response->setHeader('E-Tag',$eTag);