uuur86/dalue

PHP 数据映射器。

v0.1.1-beta 2023-05-27 22:49 UTC

This package is auto-updated.

Last update: 2024-09-07 00:02:12 UTC


README

Dalue 命名空间下的 Mapper 类提供了一个强大且灵活的数据转换和重构方法。此类允许您从给定数据集中创建新的结构,在过程中可以选择对数据进行转换。

入门指南

在开始使用 Mapper 类之前,请确保已安装包含 StrObj\StringObjects 类的库。 Mapper 类利用此类提供的数据访问和操作功能。

安装

首先,通过 Composer 安装所需的包

composer require uuur86/dalue:0.1.1-beta

示例用法

以下是如何使用 Mapper 类的示例

use Dalue\Mapper;
use StrObj\StringObjects;

// Sample data set
$data = new StringObjects([
    'user' => [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john.doe@example.com',
        'details' => [
            'age' => 30,
            'city' => 'New York'
        ]
    ]
]);

// Defining the data structure we want to transform into.
$paths = [
    'userID' => '@data/user/id',
    'userName' => '@data/user/name',
    'userDetails' => [
        'userAge' => '@data/user/details/age',
        'userCity' => '@data/user/details/city'
    ]
];

// Using the Mapper::map function to perform the transformation.
$mappedData = Mapper::map($data, $paths);

print_r($mappedData);

说明

  1. 数据初始化:
    • 使用 StringObjects 类创建一个示例数据集。
  2. 路径定义:
    • $paths 数组中定义我们想要转换成的结构。
  3. 数据转换:
    • 使用 Mapper::map 函数根据定义的路径转换数据。

输出

上面的示例将产生以下输出

Array
(
    [userID] => 1
    [userName] => John Doe
    [userDetails] => Array
        (
            [userAge] => 30
            [userCity] => New York
        )
)

高级用法

您还可以通过在映射路径中包含自定义函数来执行更复杂的转换。以下是一个示例

use Dalue\Mapper;
use StrObj\StringObjects;

$data = new StringObjects([
    'user' => [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john.doe@example.com',
        'details' => [
            'age' => 30,
            'city' => 'New York'
        ]
    ]
]);

$paths = [
    'userID' => '@data/user/id',
    'userName' => '@data/user/name',
    'userEmail' => function($data) {
        return strtoupper($data->get('user.email'));
    },
    'userDetails' => [
        'userAge' => '@data/user/details/age',
        'userCity' => '@data/user/details/city',
        'description' => function($data) {
            return $data->get('user.details.age') . ' years old, lives in ' . $data->get('user.details.city');
        }
    ]
];

$mappedData = Mapper::map($data, $paths);

print_r($mappedData);

输出

高级示例将产生以下输出

Array
(
    [userID] => 1
    [userName] => John Doe
    [userEmail] => JOHN.DOE@EXAMPLE.COM
    [userDetails] => Array
        (
            [userAge] => 30
            [userCity] => New York
            [description] => 30 years old, lives in New York
        )
)

授权协议

本项目采用 GPL-3.0-or-later 许可协议。有关详细信息,请参阅 授权协议 文件。

作者

Uğur Biçer - @uuur86

贡献

如果您想为此项目做出贡献,您可以通过发送 pull 请求。我们希望所有贡献者都遵循我们的 行为准则

联系方式

您可以通过电子邮件联系我: contact@codeplus.dev

错误

您可以通过 GitHub 问题报告错误。

安全性

如果您发现安全漏洞,请通过电子邮件报告: contact@codeplus.dev

捐赠

如果您想支持我,您可以通过 GitHub 赞助人进行捐赠: https://github.com/sponsors/uuur86

相关链接