jadich/json-property

将对象属性转换为一个增强型数组

0.1.2 2020-04-02 01:30 UTC

This package is auto-updated.

Last update: 2024-08-29 04:03:30 UTC


README

Build Status Latest Version HHVM Status

JsonProperty

JsonProperty提供了一个简单的接口,用于将键值对存储在模型的单个列中。这对于存储元数据或任何没有标准结构的数据非常有用。数据在保存时会自动序列化为JSON。

安装

使用composer安装包

composer require jfadich/json-property

要求

  • PHP >= 5.5.9

配置

  1. JsonPropertyTrait特质添加到模型
  2. 设置jsonProperty属性。这是将被调用来访问JsonProperty对象的方法的名称。您可以将此设置为数组以在单个模型上启用多个属性。
    namespace App;
    
    use Jfadich\JsonProperty\JsonPropertyTrait;
    use Jfadich\JsonProperty\JsonPropertyInterface;
    
    class SampleModel implements JsonPropertyInterface
    {
        use JsonPropertyTrait;
        protected $jsonProperty = 'meta';
    }

使用

调用模型上名为您设置的$jsonProperty的值的任何方法来访问存储在JSON字符串中的数据

$model = new SampleModel();

$model->meta()->set('key', 'value');
$value = $model->meta()->get('key'); // 'value'
$value = $model->meta('key'); // 'value'

可用方法

has($key)

检查是否存在给定键的值

if($model->meta()->has('keyName')) {
    // Do something
}

get( $key, $default = null )

获取一个值,如果它不在数组中,则使用默认值。您可以使用点符号来访问嵌套数组。

set($key, $value)

设置/更新给定的键/值对。

merge( array $values, array $allowedKeys = [] )

将给定的数组合并到保存的对象中。除非键包含在白名单中,否则不会添加不存在于原始对象中的键。

push( $key, $value )

如果给定键的值是数组,则将值推送到数组中。

forget($key)

从数组中删除元素。这将自动持久化

all()

获取数组中的所有元素

示例

对象的属性将始终是一个最新的JSON字符串,因此您可以使用您选择的任何持久化方法。

$model = new SampleModel();

// Use dot notation to access nested values
$model->meta()->set('book.title', 'Cracking the Coding Interview');
$model->meta()->set('book.author', 'Gayle Laakmann McDowell');

// $model->meta
// { "book":{"title": "Cracking the Coding Interview", "author": "Gayle Laakmann McDowell"} }
//
// $model->meta()->all()
// array:3 [
//   "book" => array:2 [
//     "title" => "Cracking the Coding Interview"
//     "author" => "Gayle Laakmann McDowell"
//   ]
// ]

定制

JsonProperty对象保持模型上的属性与当前的JSON字符串同步。如果您想在更新时自动持久化数据,请随意覆盖模型上的saveJsonString()方法。

public function saveJsonString($property, $jsonString)
{
    parent::saveJsonString($property, $jsonString);

    $this->saveToSQL(); // Persist to the database or any other method
}