PHP项目ThinkPHP响应对象与格式

wen PHP项目 3

本文目录导读:

PHP项目ThinkPHP响应对象与格式

  1. 响应对象基础
  2. 常用响应格式
  3. 响应头与状态码设置
  4. 响应拦截与处理
  5. Ajax请求响应
  6. 响应缓存
  7. 常见使用场景
  8. Tailwind CSS 响应式设计配合

在ThinkPHP框架中,响应对象和格式处理是MVC架构中视图层的重要组成部分,下面详细介绍ThinkPHP中的响应对象与格式处理机制。

响应对象基础

响应类继承关系

// ThinkPHP 6/8 中的响应类结构
think\Response (基类)
├── think\response\Html (HTML响应)
├── think\response\Json (JSON响应)
├── think\response\Jsonp (JSONP响应)
├── think\response\Redirect (重定向)
├── think\response\View (视图响应)
├── think\response\Xml (XML响应)
└── think\response\Download (下载响应)

创建响应对象

namespace app\controller;
use think\Response;
use think\response\Json;
use think\response\View;
class User
{
    // 使用助手函数
    public function index()
    {
        // 返回JSON响应
        return json(['name' => 'thinkphp', 'status' => 1]);
        // 返回HTML响应
        return response('Hello World');
        // 返回视图
        return view('index/index', ['name' => 'thinkphp']);
        // 返回XML
        return xml(['name' => 'thinkphp']);
        // 返回JSONP
        return jsonp(['name' => 'thinkphp']);
    }
    // 使用Response对象
    public function create()
    {
        $response = Response::create(['name' => 'thinkphp'])
            ->code(200)
            ->header(['Content-Type' => 'application/json'])
            ->contentType('application/json');
        return $response;
    }
}

常用响应格式

JSON响应

namespace app\controller;
class Api
{
    // 基本JSON响应
    public function jsonData()
    {
        $data = [
            'code' => 0,
            'msg'  => 'success',
            'data' => [
                'id'   => 1,
                'name' => 'ThinkPHP'
            ]
        ];
        return json($data);
    }
    // 带状态码的JSON
    public function jsonWithCode()
    {
        return json(['error' => 'Not Found'], 404);
    }
    // JSON响应头设置
    public function jsonWithHeader()
    {
        return json($data)
            ->header([
                'Authorization' => 'Bearer token',
                'X-Custom-Header' => 'Custom Value'
            ]);
    }
    // 中文不转义
    public function jsonUnicode()
    {
        return json($data, 200, ['JSON_UNESCAPED_UNICODE' => true]);
    }
}

XML响应

namespace app\controller;
class XmlController
{
    public function xmlData()
    {
        $data = [
            'name' => 'ThinkPHP',
            'version' => '6.0',
            'date' => '2024-01-01'
        ];
        return xml($data);
    }
    // 自定义XML根节点
    public function customXml()
    {
        return xml($data, 200, ['root' => 'application']);
    }
}

下载响应

namespace app\controller;
use think\response\File;
class Download
{
    // 文件下载
    public function download()
    {
        $file = new File('path/to/file.zip');
        return $file->name('download.zip');
    }
    // 下载助手函数
    public function quickDownload()
    {
        return download('path/to/file.pdf', 'document.pdf');
    }
}

响应头与状态码设置

设置响应头

namespace app\controller;
class ResponseHeader
{
    public function setHeaders()
    {
        // 方式一:链式设置
        return json($data)
            ->header('Cache-Control', 'no-cache')
            ->header('X-Powered-By', 'ThinkPHP');
        // 方式二:数组设置
        $headers = [
            'Content-Type' => 'application/json',
            'Cache-Control' => 'no-store',
            'Access-Control-Allow-Origin' => '*'
        ];
        return json($data)->header($headers);
        // 方式三:批量设置
        return json($data)->header([
            'Header1' => 'Value1',
            'Header2' => 'Value2',
        ])->contentType('application/json');
    }
    // 内容类型
    public function contentType()
    {
        return json($data)->contentType('text/html');
    }
}

设置状态码

namespace app\controller;
class StatusCode
{
    public function setStatus()
    {
        // 方式一:直接设置
        return json(['error' => 'Unauthorized'], 401);
        // 方式二:链式调用
        return json(['error' => 'Not Found'])->code(404);
        // 方式三:不同状态码对应不同响应
        return json($data)->code($this->httpCode);
    }
    // 根据业务设置HTTP状态码
    public function restful()
    {
        // 创建成功
        if ($result) {
            return json(['msg' => 'created'], 201);
        }
        // 参数错误
        return json(['msg' => 'bad request'], 400);
    }
}

响应拦截与处理

全局响应处理

// app/middleware/ResponseMiddleware.php
namespace app\middleware;
use think\Response;
class ResponseMiddleware
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        // 统一处理响应
        if ($response instanceof Response) {
            // 添加通用响应头
            $response->header([
                'Server' => 'ThinkPHP',
                'X-Frame-Options' => 'SAMEORIGIN'
            ]);
            // 如果是JSON响应,统一封装格式
            if ($response instanceof \think\response\Json) {
                $content = json_decode($response->getContent(), true);
                $response->data([
                    'code' => isset($content['code']) ? $content['code'] : 0,
                    'msg'  => isset($content['msg']) ? $content['msg'] : 'success',
                    'data' => $content
                ]);
            }
        }
        return $response;
    }
}

数据转换

namespace app\controller;
class DataTransform
{
    // 数据格式转换
    public function transform()
    {
        $user = User::find(1);
        // 转换为数组
        $array = $user->toArray();
        // 转换为JSON
        return json($user->toJson());
        // 自定义字段
        return json([
            'id'    => $user->id,
            'name'  => $user->name,
            'email' => $user->email
        ]);
    }
    // 批量转换
    public function batchTransform()
    {
        $users = User::select();
        // 使用collection
        return json(collection($users)->map(function($user) {
            return [
                'id'   => $user->id,
                'name' => $user->name
            ];
        }));
    }
}

Ajax请求响应

namespace app\controller;
class AjaxController
{
    // Ajax请求响应
    public function ajaxResponse()
    {
        if ($this->request->isAjax()) {
            $result = ['status' => 1, 'msg' => 'success'];
            // JSON格式
            return json($result);
            // JSONP格式(需指定callback参数)
            return jsonp($result, 200, ['callback' => 'handle']);
        }
        // 非Ajax请求返回视图
        return view('index');
    }
    // 判断请求类型返回不同格式
    public function multiFormat()
    {
        $data = ['name' => 'ThinkPHP'];
        // 根据请求类型返回不同格式
        if ($this->request->isAjax()) {
            return json($data);
        }
        if ($this->request->isPjax()) {
            return view('pjax_template', $data);
        }
        return view('full_template', $data);
    }
}

响应缓存

namespace app\controller;
class CacheResponse
{
    // 缓存响应
    public function cachedResponse()
    {
        $data = cache('user_data');
        if (!$data) {
            $data = User::select();
            cache('user_data', $data, 3600);
        }
        return json($data);
    }
    // 使用响应缓存头
    public function cacheHeaders()
    {
        return json($data)->header([
            'Cache-Control' => 'public, max-age=3600',
            'Expires' => gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT'
        ]);
    }
}

常见使用场景

API接口响应封装

namespace app\common;
class ApiResponse
{
    /**
     * 成功响应
     */
    public static function success($data = [], $msg = 'success')
    {
        return json([
            'code' => 0,
            'msg'  => $msg,
            'data' => $data
        ]);
    }
    /**
     * 失败响应
     */
    public static function error($msg = 'error', $code = 400)
    {
        return json([
            'code' => $code,
            'msg'  => $msg,
            'data' => []
        ], $code);
    }
}
// 使用方式
namespace app\controller;
class OrderController
{
    use \app\common\ApiResponse;
    public function create()
    {
        try {
            $result = Order::create($this->request->post());
            return $this->success($result, '订单创建成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }
}

文件流响应

namespace app\controller;
use think\Response;
class FileController
{
    // 图片验证码
    public function captcha()
    {
        $response = Response::create(function() {
            // 生成验证码图片
            $image = imagecreatetruecolor(100, 30);
            // ... 绘制验证码
            imagepng($image);
            imagedestroy($image);
        }, 'image');
        return $response->contentType('image/png');
    }
    // CSV导出
    public function exportCsv()
    {
        $data = [
            ['id', 'name', 'email'],
            ['1', '张三', 'zhangsan@example.com'],
            ['2', '李四', 'lisi@example.com']
        ];
        $handler = fopen('php://temp', 'r+');
        foreach ($data as $row) {
            fputcsv($handler, $row);
        }
        rewind($handler);
        $csv = stream_get_contents($handler);
        fclose($handler);
        return response($csv)
            ->contentType('text/csv')
            ->header('Content-Disposition', 'attachment; filename=export.csv');
    }
}

Tailwind CSS 响应式设计配合

<!-- 在视图中使用 Tailwind CSS -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <!-- API响应状态显示 -->
    <div class="max-w-7xl mx-auto px-4 py-6">
        <div id="api-response" class="space-y-4">
            <!-- 响应内容将在这里动态渲染 -->
        </div>
    </div>
    <script>
        // AJAX请求处理响应
        fetch('/api/user/1')
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    // 成功响应
                    document.getElementById('api-response').innerHTML = `
                        <div class="bg-green-50 border-l-4 border-green-500 p-4">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-green-400" ...></svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-green-800">${data.msg}</p>
                                </div>
                            </div>
                        </div>
                    `;
                }
            });
    </script>
</body>
</html>

ThinkPHP的响应对象和格式处理提供了:

  • 灵活的响应格式:JSON、XML、HTML、文件等
  • 链式操作方法:header、code、contentType等
  • 状态码管理:HTTP状态码的智能设置
  • 响应拦截和统一处理机制
  • 缓存支持
  • 各种业务场景的支持

使用这些特性可以构建高效、灵活的Web应用和API接口。

抱歉,评论功能暂时关闭!