【问题标题】:How to mimic Eloquent model conversions to json when return to requests?返回请求时如何模仿 Eloquent 模型到 json 的转换?
【发布时间】:2023-04-01 23:20:01
【问题描述】:

我正在创建一个这样的自定义类:

<?php namespace App\Models\NonDbModels;

class BaseNonDbModel
{
    public function __construct($values)
    {
        foreach ($values as $key => $value)
        {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }

    public function toArray()
    {
        return get_object_vars($this);
    }

    public function toJson()
    {
        return json_encode($this->toArray());
    }

    public function __toString() : string
    {
        return $this->toJson();
    }
}

在控制器中,我会将对象返回给这样的请求

$object = new BaseNonDbModel();
return $object;

它将正确返回一个 json 字符串,但返回类型将是 HTML。但如果它是 Eloquent 模型,响应类型将是 application/json。我如何模仿 Eloquent 模型的行为,我尝试阅读 Eloquent 代码,但似乎他们没有做任何不同的事情,是否在 Laravel 核心中识别 Eloquent 并将响应类型更改为 application/json ?

我知道我可以回来

return Response::json($object)

或者可能为所有请求创建一个强制 application/json 类型的中间件,但这不是我所追求的,我更喜欢像 Eloquent 模型一样舒适地返回 $object。

谢谢!

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以创建一个 GeneralResponse 特征

    <?php
    
    namespace App\Traits;
    
    use Illuminate\Http\JsonResponse;
    use Symfony\Component\HttpFoundation\Response;
    
    
    trait GeneralResponse
    {
        public function response(
            $status = true,
            $message = null,
            $data = [],
            $code = Response::HTTP_OK,
            $display = false,
            $code2 = null
        ): JsonResponse {
            $response = [
                'status'  => $status,
                'display' => $display,
            ];
    
            if($message) {
                $response['message'] = $message;
            }
            if($code2) {
                $response['code'] = $code2;
            }
            if($data) {
                $response['data'] = $data;
            }
            return response()->json($response, $code);
        }
    
    
    }
    

    在你必须返回响应的控制器中使用它:

    use GeneralResponse;
    
    return $this->response(true, 'message', null, Response::HTTP_OK, true);
    

    如果您需要更多说明,请告诉我。

    【讨论】:

    • 感谢您的见解。然而,这也不是我所追求的。我想要一个解决方案,控制器端不需要做任何事情,只需返回对象,返回 Eloquent 对象的工作原理。我怀疑这是我们可以用模型对象本身做的事情
    • 是的,但在这种情况下,如果 Laravel 在与 eloquent 相关的新版本中进行任何更新,那么您的应用程序可能会停止工作。所以更好的方法是使用一些特征或界面
    • 我非常怀疑。如果我们可以准确地模仿 Laravel 对 Eloquent 对象所做的事情,除非 Laravel 正在改变 Eloquent,否则它不会崩溃
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多