flashport/laravel-json-marshaller

lib flashport/json-marshaller 的 laravel 封装

v0.12.3 2024-09-12 09:19 UTC

This package is auto-updated.

Last update: 2024-09-12 09:19:29 UTC


README

这是一个为 json-marshaller 库提供的 laravel 封装。

安装

    composer require flashport/laravel-json-marshaller

使用方法

使用这个库主要有两种方式,可以直接使用现有的目标转换对象而不修改它们,只修改执行转换的模型。

选项 1:直接在模型上

$casts 数组中,指定 JsonMarshallable::class 和冒号后面的目标类。这将确保目标类被作为参数传递给 Marshaller。

/**
 * The attributes that should be cast.
 *
 * @var array<string, string>
 */
protected $casts = [
    'metadata'      => JsonMarshallable::class . ":" . Metadata::class,
    'customFields'  => JsonMarshallable::class . ":" . CustomField::class,
    'active'        => 'bool',
];

选项 2:在目标类上

目标类

确保在您的目标类中扩展 AsJsonMarshallable 类。

use LaravelJsonMarshaller\Castables\AsJsonMarshallable;

class CustomField extends AsJsonMarshallable
{
    //...
}

模型

在模型上,只需指定您想要转换成的目标类名。

/**
 * The attributes that should be cast.
 *
 * @var array<string, string>
 */
protected $casts = [
    'metadata'      => Metadata::class,
    'customFields'  => CustomField::class,
    'active'        => 'bool',
];