php - 解析具有变形关系的资源类
问题描述
问题
我有具有变形关系的模型,并且那些不同类型的关系具有完全不同的 json 资源要返回。所以我试图找到一种方法来解决正确的关系类并将其与基本模型的资源一起返回。
例如,如果我有评论和变形关系“可评论”,其中包含汽车和司机的模型实例。现在,如果我请求一些评论,我将能够返回存储到 CarResource 或 PeopleResource 中的正确 json 响应。
{
id: 1,
text: 'A comment',
commentable_type: 'Car', // could be car or driver
commentable_data: {
model: 'Ford',
year: 2019
},
id: 2,
text: 'An another comment',
commentable_type: 'Driver',
commentable_data: {
name: 'Jon Doe',
active: true
},
}
试图解决
我尝试使用以下功能,但出现错误。
public function toArray($request)
{
$modelClass = app(__NAMESPACE__ . '\\' . class_basename($this->commentable) . 'Resource');
return [
'id' => $this->id,
'text' => $this->text,
'commentable_type' => class_basename($this->commentable),
'commentable_data' => new $modelClass($this->commentable),
];
}
如果解决的课程不存在,我当然会得到
反射异常 (-1)
类 App\Http\Resources\CarResource 不存在
但是如果该类存在,我会收到以下错误
照亮\合同\容器\ BindingResolutionException
类 Illuminate\Http\Resources\Json\JsonResource 中无法解析的依赖解析 [Parameter #0 [ $resource ]]
问题
你怎么看?您有任何解决方案或建议,例如如何更好地管理这个问题?
解决方案
好的,我通过深入研究 Laravel 找到了解决方案。服务容器是我的朋友。就像BindingResolutionException说我需要$resource
使用函数为解析器提供参数makeWith()
。
$modelClass = app()->makeWith(__NAMESPACE__ . '\\' . class_basename($this->barcodable) . 'Resource', [
'resource' => $this->barcodable
]);
但是,请让我知道是否有人对改进这一点有任何想法。
推荐阅读
- c - MD5 的 C 实现给出了错误的哈希值
- reactjs - AWS 放大自定义问候语
- python - 如何将模块内部进度状态填充到另一个模块?
- go - 将 CORS 标头添加到 gqlgen 默认示例中?
- javascript - 异步函数不等待并继续
- mysql - 如何在 WHERE 子句(MySQL)中使用 VIEW?
- swift - 当我尝试改变存储有颜色值的变量时出现错误
- azure - 来自 Azure 应用程序网关 V2 的多个登录提示
- ajax - Laravel 关系方法从数组中获取一些总数
- angular - 在 ion-virtual-scroll 之前添加内容时出现 ionic 4 问题