承接 om/from-array 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

om/from-array

最新稳定版本:v2.0.1

Composer 安装命令:

composer require om/from-array

包简介

fromArray trait allow create objects instances loaded with initial data array

README 文档

README

Packagist Version Packagist License Packagist Downloads

FromArray Data Loader Trait

Introduction

FromArray is a lightweight PHP trait that enables effortless object hydration from associative arrays. It is especially useful in scenarios where data needs to be mapped into strongly-typed objects, such as when working with APIs, form inputs, or configuration data.

With support for PHP attributes, FromArray lets you fine-tune how each property is loaded, define type expectations, and apply custom transformation logic—all while keeping your code clean and expressive.

Install

composer require om/from-array

Usage

The fromArray trait enables the creation of object instances preloaded with an initial data array:

class Example {
  use FromArray;
  public string $a;
  public string $b;
  public string $c;
}

$example = Example::fromArray(
  [
    'a' => 'value of A',
    'b' => 'value of B',
    'c' => 'value of C',
  ],
);

echo json_encode($example, JSON_PRETTY_PRINT);

And that will be the result:

{
  "a": "value of A",
  "b": "value of B",
  "c": "value of C"
}

The trait works with public properties only – private and protected properties will be ignored.

The Property, Loader and Type attributes

There are few PHP Attributes to configure the fromArray behavior:

Property

The Property attribute allows you to define a specific key (from) from the data array that will be mapped to the property.

class Example
{
    use FromArray;
    
    #[Property(from: '_id')]
    public int $id;
}

$example = Example::fromArray(['_id' => 123]);
assert($example->id === 123);

You can also customize the loader used to load the data:

function addPrefix(mixed $value) {
    return 'PREFIX_' . $value;
}

class Example
{
    use FromArray;
    
    #[Property(loader: 'addPrefix')]
    public string $name;
}

$example = Example::fromArray(['name' => 'name']);
assert($example->name === 'PREFIX_name');

Loader can also be the name of a class, an object, or any type of callable function.

For more see basic-example.php.

Loader

The Loader attribute allows you to define a specific value loader for the property. You can add global loaders to the class or to the property.

<?php
use DataLoader\Loader;use DataLoader\Property;

class MyLoader {
    public function __invoke($value, Property $property){
        return match ($property->name) {
            'id' => (int) $value,
            'names' => explode(',', $value),
            default => $value,
        }
    }
} 

#[Loader(MyLoader::class)]
class Example
{
    use FromArray;
    public mixed $id = null;
    public array $names = [];
    public string $other = '';
    
}

$example = Example::fromArray([
    'id' => '123',
    'names' => 'John,Doe,Smith'
    'other' => 'value',
]);

For more see loader-class.php or loader-property.php-

Type

The Type attribute allows you to define a specific type for the property. Types are usually auto detected, but you can force the type using the Type attribute.

class Example
{
    use FromArray;
    
    #[Type(name: Types::Int, allowNull: true, class: null)]
    public mixed $id;
}

There is one special case for the Type, you can specify Types::ArrayOfObjects type to load an array of objects with the same class. The class parameter is required in this case.

class ExampleObject {
    public function __construct(public string $name = null) {}
}

class Example
{
    use FromArray;
    
    #[Type(name: Types::ArrayOfObjects, class: ExampleObject::class)]
    public array $objects = [];
}

$example = Example::fromArray([
    'objects' => [
        ['name' => 'John'],
        ['name' => 'Doe'],
    ],
]);

See array-of-objects.php for more information.

Metadata

There is a Metadata object, that contains all the information about the class and its properties. Metadata object is singleton, but you can load instance from any type of cache.

// prepare metadata
$metadata = new Metadata();
$metadata->resolve(Example::class, MyObject::class);
$data = $metadata->getArrayCopy();

// restore singleton data
Metadata::fromCache($data);

See metadata-cache.php for more information.

Testing

How to run the tests:

composer test  # PHP tests
composr format # PHP CS Fixer

统计信息

  • 总下载量: 11.67k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 1
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 7
  • Watchers: 2
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2017-10-27