aura.http



简介

Aura HTTP包提供构建和发送HTTP响应(从服务器到客户端)的对象。


开始


实例化

最简单的方法你懂的,使用scripts/instance.php脚本获得一个新的Response对象。

<?php
$response = include '/path/to/aura.http/scripts/instance.php';

同样,你也可以把'/path/to/aura.http/src'目录添加到自动加载器中,然后手动构建Response对象:

<?php
use aura\http\Response;
use aura\http\Headers;
use aura\http\Cookies;
$response = new Response(new Headers, new Cookies);


设置内容

使用setContent()方法为Response对象设置内容:

<?php
$html = '<html>'
      . '<head><title>Test</title></head>'
      . '<body>Hello World!</body>
      . </html>';
$response->setContent($html);


设置头部

访问$headers属性(本身又是Headers集合对象)设置HTTP头部。

<?php
$response->headers->set('Header-Label', 'header value');

你也可以给setAll()方法传一个键-值数组一次性设置所有HTTP头部信息,数组键名就是HTTP头部标签,数组值一个或多个HTTP头部值。

<?php
$response->headers->setAll(array(
    'Header-One' => 'header one value',
    'Header-Two' => array(
        'header two value A',
        'header two value B',
        'header two value C',
    )
));

注意,HTTP头部标签是要经过审查和规范处理的,所以如果你输入header_foo标签,它将会被转换成Header-Foo


设置Cookie

访问$cookie属性(它本身是一个Cookie集合对象)设置cookies。向它传递cookie名,和关于该cookie的信息数组(包含cookie值)。

<?php
$response->cookies->set('cookie_name', array(
    'value'    => 'cookie value', // cookie value
    'expire'   => time() + 3600,  // expiration time in unix epoch seconds
    'path'     => '/path',        // server path for the cookie
    'domain'   => 'example.com',  // domain for the cookie
    'secure'   => false,          // send by ssl only?
    'httponly' => true,           // send by http/https only?
));

信息数组是模仿setcookies()参数名建立的。你只需提供你要用到的参数,其他的将会用null填充。

你也可以传递一个键-值数组一次性设置所有cookie,数组键名就是cookie名,数组值是cookie信息数组。

<?php
$response->cookies->setAll(array(
    'cookie_foo' => array(
        'value' => 'value for cookie foo',
    ),
    'cookie_bar' => array(
        'value' => 'value for cookie bar',
    ),
));


设置HTTP响应状态

使用setStatusCode()setStatusText()方法设置HTTP响应状态。setStatusCode()方法会自动设置已知状态码的文本。

<?php
// automatically sets the status text to 'Not Modified'
$response->setStatusCode(304);

// change the status text to something else
$response->setStatusText('Same As It Ever Was');

Response对象默认设置响应状态为'200 OK'


发送响应

如果你已经设置好了内容、头部、cookie和响应状态,你可以使用send()方法发送响应到客户端。

<?php
$response->send();

这将会使用header()函数发送所有HTTP头,使用setcookie()发送所有cookie,然后echo内容。

注意,你只能发送一次响应Response。如果你尝试再次发送,或者发送另一个带有HTTP头的响应,你将会触发Exception_HeadersSent异常。

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>