judahnator / laravel-metadata
v0.3.0
2018-08-07 16:46 UTC
Requires
- php: >=7.1
- ext-json: *
- judahnator/json-manipulator: ^1.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.12
- orchestra/testbench: ^3.6
- phpstan/phpstan: ^0.10.2
- phpunit/phpunit: ^7.2
This package is auto-updated.
Last update: 2022-02-01 13:14:17 UTC
README
此包提供了为您的应用程序模型添加“元数据”的能力。
模型设置
首先,您需要将一个 JSON 字段添加到您的模型表中。
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('{your table}', function(Blueprint $table) {
$table->json('metadata');
});
接下来,对于最基本的设置,您只需要在您的模型中使用 HasMetadata
特性。
<?php
use Illuminate\Database\Eloquent\Model;
use judahnator\LaravelMetadata\HasMetadata;
class MyModel extends Model
{
use HasMetadata;
}
就这样。现在您可以为模型添加任意数量的元数据,这些数据不会持久化到数据库,直到您保存模型。
基本用法
您可以通过 meta
访问器访问模型元数据。此访问器始终返回一个 judahnator\JsonManipulator\JsonBase
对象。您可以像访问任何其他对象一样访问其值。
当处理嵌套属性时,无论是数组中的属性还是对象中的属性,您将根据适当的情况与一个 judahnator\JsonManipulator\JsonArray
或 judahnator\JsonManipulator\JsonObject
对象一起工作。
<?php
$MyModel = MyModel::find(123);
// You can work with values directly
$MyModel->meta->foo = 'bar';
// You can also work with nested arrays and objects
$MyModel->meta->nested_array = ['foo', 'bar'];
$MyModel->meta->nested_object = (object)['keyed' => 'item'];
// Be aware that when retrieving arrays and objects, they are going to be represented with the JsonBase class.
/** @var \judahnator\JsonManipulator\JsonArray $nested_array */
$nested_array = $MyModel->meta->nested_array;
/** @var \judahnator\JsonManipulator\JsonObject $nested_object */
$nested_object = $MyModel->meta->nested_object;
// Because of how this library works internally, changing returned values changes the root value as well.
$nested_array[] = 'baz';
echo $MyModel->meta->nested_array[2]; // 'baz'
// Remember to save the model to make the metadata persist!
$MyModel->save();
更高级的用法
除了可以拉入模型的特性之外,您还可以基于 MetadataModel
类创建模型。这是完全可选的,但允许您“捷径”部分元数据存储。
您必须在模型中定义受保护的 $metadata
数组。它以 key=>value 对的形式格式化,其中键是存储,值是存储是数组还是对象。
<?php
use judahnator\LaravelMetadata\MetadataModel;
class MyModel extends MetadataModel
{
protected $metadata = [
'profile' => 'object',
'hobbies' => 'array'
];
}
$MyModel = MyModel::find(123);
$MyModel->profile->youngest_grandchilds_name = 'Jimmy';
$MyModel->hobbies[] = 'hiking';
$MyModel->hobbies[] = 'coding';