cupcoffee/reify

此包的最新版本(0.4)没有提供许可证信息。

映射库

0.4 2022-05-13 13:35 UTC

This package is auto-updated.

Last update: 2024-09-13 18:26:14 UTC


README

Reify 是一个用于激活对象的轻量级包。当实现 API 客户端或创建应用程序中的抽象层时,这可能很有用。

安装

在此处插入有关生产使用警告

composer require reify/reify:"dev-master"

入门

假设你有一个包含有关人员信息的数据集。

{
	"name": "Leroy",
	"profession": "Developer",
	"colleagues": [
		{
			"name": "Peter",
			"profession": "Developer"
		},
		{
			"name": "Sandra",
			"profession": "Developer"
		}
	],
	"spouse": null
}

你希望在应用程序中使用这些数据,但仅使用 json_decode 将会得到一个没有任何类型和无法添加功能的基本对象。

Reify 可以自动将数据映射到任何你想要的类。让我们尝试使用我定义的以下 Person 类来映射我们的数据。

use Reify\Reify;

$person = Reify::json($data)->to(Person::class);
use Reify\Attributes\Construct;
use Reify\Attributes\Type;

class Person {
    public string $name;
    
    #[Construct]
    public Profession $profession;
    
    #[Type(Person::class)]
    public array $colleagues;
    
    public ?Person $spouse;
    
    public object $meta;
}

很酷吧?让我们分析一下这里发生了什么。

class Person {
    /**
     * Using PHP 8 syntax we can define a type for each property
     * Reify supports all scalar values and custom types defined by you
     */
    public string $name;
    
    
    /**
     * If you have a single value that needs to be mapped to a type
     * You can use the Construct attribute. This will call the constructor with the value instead of mapping it.
     */
    #[Construct]
    public Profession $profession;
    
    /**
     * Unfortunately PHP does not have Generics.
     * We can however still define a type using the Type attribute.
 *   * Reify will try to map each value in the list to the given value
     */
    #[Type(Person::class)]
    public array $colleagues;

    /**
    * Not sure if the data is available? 
    * Reify will take your nullables in to account. 
    */    
    public ?Person $spouse;
    
    /**
    * You don't know what the data is going to look like? 
    * Reify supports mapping to plain objects aswell. 
    */
    public object $meta;
}

结论

Reify 是我多年来一直在摸索的概念。这是一个我经常在我的项目中使用的简单概念。

这个包是用 PHP 8 特性构建的,以便我了解它们并玩转新的 Attributes。结果我发现我非常喜欢元编程以及用它们创建开发者工具。

构建 Reify 还让我有机会了解 PestPHP 并学习更多关于为我的代码编写测试的知识。

运行测试

vendor/bin/pest

替代方案

如果你正在寻找我本人使用的值得生产推荐,请参阅以下内容