hyperf响应处理

发布时间:2021-12-30 10:30:17 阅读:1531次

在hyperf中如何输出json格式 , xml格式 及 raw 格式

如何实现跳转

以下如何生成cookie

如何下载

以下为控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\HttpMessage\Cookie\Cookie;

/**
 * @AutoController();
 */
class IndexController
{
    /**
     * 返回json格式示例
     */
    public function json(ResponseInterface $response):Psr7ResponseInterface
    {
        $data = [
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        return $response->json($data);
    }

    /**
     * 返回xml格式示例
     */
    public function xml(ResponseInterface $response):Psr7ResponseInterface
    {
        $data = [
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        return $response->xml($data);
    }

    /**
     * 返回raw格式示例
     */
    public function raw(ResponseInterface $response):Psr7ResponseInterface
    {
        $data =[
            'name'=>'huyongjian',
            'qq'=>'308830232@qq.com'
        ];
        $data = json_encode($data);
        return $response->raw($data);
    }

    /**
     * redirect示例
     *
     */
    public function redirect(ResponseInterface $response):Psr7ResponseInterface
    {
        return $response->redirect('/index/json');
    }

    /**
     *cookie设置示例
     */
    public function cookie(ResponseInterface $response):Psr7ResponseInterface
    {
        $cookie = new Cookie('name','huyongjian');
        return $response->withCookie($cookie)->withContent('Hello Hyperf cookie is ok');
    }

    /**
     * 文件下载示例
     */
    public function download(ResponseInterface $response):Psr7ResponseInterface
    {
        return $response->download(BASE_PATH . '/public/download.txt', 'download.txt');
    }
}

以下为运行结果


添加download.txt public/download.txt

download test
浏览器访问测试

json

http://118.195.173.53:9501/index/json
结果

{"name":"huyongjian","qq":"308830232@qq.com"}
xml

http://118.195.173.53:9501/index/xml
结果

<root>
<name>huyongjian</name>
<qq>308830232@qq.com</qq>
</root>
raw

http://118.195.173.53:9501/index/raw
结果

{"name":"huyongjian","qq":"308830232@qq.com"}
redirect

http://118.195.173.53:9501/index/redirect
结果

{"name":"huyongjian","qq":"308830232@qq.com"}
cookie

http://118.195.173.53:9501/index/cookie
结果

Hello Hyperf cookie is ok
Application>Cookies 可以看到设置的cookie值

文件下载

http://118.195.173.53:9501/index/download

本文转载 https://www.cnblogs.com/hu308830232/p/15304155.html

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:hyperf响应处理 出自老鄢博客 | 欢迎分享