judahnator / laravel-json-manipulator
judahnator/json-manipulator 库的 Laravel 扩展
v3.0.1
2021-01-21 15:52 UTC
Requires
- php: >=7.4
- illuminate/support: ^6.0|^7.0|^8.0
- judahnator/json-manipulator: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16.7
- orchestra/testbench: ^6.5
- phpstan/phpstan: ^0.12.58
- phpunit/phpunit: ^9.4
README
是什么?
这是对另一个 json-manipulator 库的扩展。如果您想了解详细信息,请阅读该库的文档。
此库存在的基本原因是 Laravel 通过 PHP 重载提供了对 JSON 列的访问,这意味着您不能直接像操作原生 PHP 对象一样与数据交互。
此库通过提供可在模型中使用的 trait 解决了这个问题。通过添加您要操作的字段的访问器,您可以更轻松地处理数据。
安装
通过 composer
composer require judahnator/laravel-json-manipulator
使用方法
使用方法非常简单。
- 在模型的顶部,您需要
use HasJsonAttributes;
。 - 对于每个 JSON 属性,您需要编写一个访问器。
- 对于 JSON 对象:
return $this->load_json_object();
- 对于 JSON 数组:
return $this->load_json_array();
- 对于 JSON 对象:
如果访问器名称不是数据库中的字段,或者您希望引用自定义属性,您可以传递一个属性名称来使用。
您还可以传递可选的第二个属性来设置如果属性在模型中尚不存在,则默认值。
return $this->load_json_object(
'my_custom_attribute_name',
'{"with a": "custom default"}'
);
示例
假设您有一个 "Friend" 模型。
您的朋友有多种联系方式,这些联系方式存储为一个对象。该字段在数据库中可以命名为 contact_methods
。
{
"email": "friend@example.com",
"mobile": "208-555-1234"
}
您的朋友还有一个喜欢的食物数组。假设它们在数据库中存储为 favorite_foods
。
[
"Pizza",
"Celery",
"Apple"
]
有了以上,您的模型可能看起来像这样。
<?php
use \Illuminate\Database\Eloquent\Model;
use judahnator\JsonManipulator\JsonArray;
use judahnator\JsonManipulator\JsonObject;
use judahnator\LaravelJsonManipulator\HasJsonAttributes;
class Friend extends Model
{
use HasJsonAttributes;
/**
* Accessor to return the contact_methods attribute
* @return JsonObject
*/
public function getContactMethodsAttribute(): JsonObject
{
return $this->load_json_object();
}
/**
* Accessor to return the favorite_foods attribute
* @return JsonArray
*/
public function getFavoriteFoodsAttribute(): JsonArray
{
return $this->load_json_array();
}
}
您现在可以使用模型上的这些字段,就像使用任何其他原生 PHP 数组或对象一样。
<?php
$friend = Friend::find('Judah');
$friend->contact_methods->mastodon = 'judahnator@mastodon.xyz';
$friend->favorite_foods[] = 'cake';
unset($friend->favorite_foods[1]); // nobody likes celery
$friend->save();