Http response class php

Мой путь в мире web-devel

Начинающие веб-разработчики (в том числе и я) не понимают основную функцию веб-приложения (не только php). А ведь это очень важно и в то же время очень просто. Основная функция веб-приложения получить запрос от клиента, подготовить ответ (здесь выполняются различные действия получения данных и их обработки), вернуть ответ клиенту.

Очень часто запрос и ответ реализуются в веб-приложениях в виде классов Request и Response. Тогда все что нужно будет приложению это определить путь запроса Request и вернуть соответствующий пути ответ Response. UML-диаграмма классов Request и Response представлена ниже:

Как мы видим в классе Request есть три метода:

  • getPathInfo() — метод получения пути запроса
  • find(key) — поиск параметра запроса по ключу key
  • has(key) — проверка существования параметра в запроса
  • Response(content, status_code, headers) — конструктор класса, принимает в качестве параметров один обязательный содержимое ответа и два не обязательных status_code (200 — по умолчанию), headers — массив HTTP-заголовков
  • setStatusCode(status_code) — из названия понятно что этот метод делает
  • setHeader(header) — то же
  • send() — отправка ответа на вывод
  • content — содержимое ответа
  • status_code — код ответа
  • headers — массив, содержащий HTTP-заголовки ответа
 /** * Поиск и получение значения параметра зпроса * по ключу * * @param string $key искомый ключ параметра запроса * @return mixed значение параметра * или null если параметр не существует */ public function find($key) < if ( key_exists($key, $_REQUEST) ) return $_REQUEST[$key]; else return null; >/** * Проверяет существование параметра в запросе * по его ключу * * @param string $key проверяемый ключ * @return boolean */ public function has($key) < return key_exists($key, $_REQUEST); >> ?>
content = $content; $this->status_code = $status_code; $this->headers = $headers; > public function setStatusCode($status_code) < $this->status_code = $status_code; > public function setHeader($header) < $this->headers[] = $header; > public function send() < // выслать код статуса HTTP header('HTTP/1.1 ' . $this->status_code); // отправить заголовки HTTP foreach ( $this->headers as $header ) header($header); // отправить содержимое ответа echo $this->content; > > ?>

Пример использования этих классов index.php:

getPathInfo(); // создаем ответ в соответствии с путем запроса if ( $path_info == '/' ) $response = new Response('Main page'); else if ( $path_info == 'contact') $response = new Response('Contact page'); else $response = new Response('Not found 404', 404); // возвращаем ответ клиенту $response->send(); ?>

Источник

Читайте также:  Php интервал в цикле

FuelPHP, a PHP 5.3 Framework Documentation

The response class contains the methods to deal with HTTP response and browser output.

Setting the Status Header

The status header is treated as a «special» header in Fuel. You do not set it as you would other headers. The status header is set as follows in the controller:

$response = new Response($body, 404);

Setting the Status Header and other headers

$headers = array ( 'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', 'Pragma' => 'no-cache', ); $response = new Response($body, 404, $headers);

forge($body = null, $status = 200, array $headers = array())

The forge method creates a new instance of the Response class.

// create a response object, use a View as body, and a 404 NOT FOUND status code return Response::forge(View::forge('errors/404page'), 404);

redirect($url = », $method = ‘location’, $redirect_code = 302)

The redirect method offers different methods of redirecting to a new URL.

// use a URL Response::redirect('http://example.com/home', 'refresh'); // or use a relative URI Response::redirect('site/about');

This method supports wildcard replacement in the URL. See Uri::segment_replace() for more information. You can disable this by setting response.redirect_with_wildcards to false in your applications config.php.

redirect_back($url = », $method = ‘location’, $redirect_code = 302)

The redirect_back method allows you to redirect back to the page you came from, and offers different methods of redirecting to a new URL. If the previous page is not part of your application (i.e. the user came from another website), or no URL is given, it will redirect to the application homepage.

// redirect back. If there is no 'back', go to the dashboard page Response::redirect_back('/dashboard', 'refresh');

This method supports wildcard replacement in the URL. See Uri::segment_replace() for more information. You can disable this by setting response.redirect_with_wildcards to false in your applications config.php.

set_status($status = 200)

The set_status method allows you to update the HTTP status code set on a Response object.

$response = new Response(); // This will be a NOT FOUND response $response->set_status(404);

set_header($name, $value, $replace)

The set_header method allows set custom HTTP headers.

$response = new Response(); // We'll be outputting a PDF $response->set_header('Content-Type', 'application/pdf'); // It will be called downloaded.pdf $response->set_header('Content-Disposition', 'attachment; filename="downloaded.pdf"'); // Set no cache $response->set_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate'); $response->set_header('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT'); $response->set_header('Pragma', 'no-cache'); // More examples $response->set_header('Content-Language', 'en'); $response->set_header('Content-Type', 'text/html; charset=utf-8'); return $response;

Note that names are unique, overwriting each other if the same name is used.

get_header($name = null)

The get_header method allows you to retrieve a custom HTTP headers set previously.

$response = new Response(); $response->set_header('Pragma', 'no-cache'); // returns 'no-cache' $header = $response->get_header('Pragma'); // returns array('Pragma' => 'no-cache') $header = $response->get_header();

body($value = false)

The body method allows get the current response body, or set a new one.

$response = new Response(); $response->body('This is the response body'); // returns 'This is the response body' $body = $response->body();

send_headers()

The send_headers method sends the set headers out to the browser, including the HTTP status of the request.

Note that you normally don’t have to call this method manually. Fuel will take care of this as part of processing the request.

send($send_headers = false)

The send method sends the response body to the output buffer (i.e. it is echo’d out).

// echo whatever the response body is $response->send();

Note that you normally don’t have to call this method manually. Fuel will take care of this as part of processing the request.

© FuelPHP Development Team 2010-2014 — FuelPHP is released under the MIT license.

Источник

Оцените статью