跳至主要内容

响应

响应表示服务器对客户端的HTTP响应。下面列出了几种不同类型的作,每种类型都展示了控制器动作响应的构建示例。

字符串

要返回简单的字符串响应,请使用该服务。response

public function indexAction()
{
    return $this['response']->create('My content');
}

渲染视图

Pagekit可以渲染视图并返回响应。只需返回一个数组,键设置为包含标题和视图名称的数组。$view

数组中的所有其他参数都会在视图中被访问。了解更多关于视图和模板的信息

public function indexAction($name = '')
{
    return [
        '$view' => [
            'title' => 'Hello World',
            'name' => 'hello:views/index.php',
        ],
        'name' => $name
    ];
}

如果你不想渲染如下面所述的主题回应,可以在数组中设置。'layout' => false$view

主题

主题响应将控制器的结果嵌入到周围的布局中,通常由主题定义。只需从控制器返回字符串即可。

public function indexAction()
{
    return 'My content';
}

JSON

从控制器返回 JSON 响应有两种方式:

如果作返回的数组或实现 的对象,则会自动生成 a。\JsonSerializableJsonResponse

public function jsonAction()
{
    return ['error' => true, 'message' => 'There is nothing here. Move along.'];
}

当然,这项服务也可以用来实现同样的效果。response

public function jsonAction()
{    
    return $this['response']->json(['error' => true, 'message' => 'There is nothing here. Move along.']);
}

重定向

使用重定向回应来重定向用户。

public function redirectAction()
{
    return $this['response']->redirect('@hello/greet/name', ['name' => 'Someone']);
}

自定义响应和错误页面

返回任何自定义的 HTTP 响应,使用 。create

public function forbiddenAction()
{
    return $this['response']->create('Permission denied.', 401);
}

流式响应允许将内容流回客户端。它以回调函数作为第一个参数。在回调过程中,会直接向客户端发出一个呼叫。flush

public function streamAction()
{
    return $this['response']->stream(function() {
        echo 'Hello World';
        flush();
        echo 'Hello Pagekit';
        flush();
    });
}

下载

下载响应允许你向客户端发送文件。它会在大多数浏览器中强制设置“另存为”对话框。Content-Disposition: attachment

public function downloadAction()
{
    return $this['response']->download('extensions/hello/extension.svg');
}