rfx/cast

将 stdClass 或任何其他类转换为另一个类

v1.1.0 2022-05-18 16:49 UTC

This package is auto-updated.

Last update: 2024-09-15 22:22:09 UTC


README

Minimum PHP version: 7.4.0

关于

允许您将 stdClass(或任何其他类)转换为其他类。

安装

composer require rfx/cast

用法

问题

因此,您收到了一个美丽的对象,您想使用它

stdClass Object
(
    [name] => home
    [at] => stdClass Object
        (
            [x] => 4
            [y] => 5
        )
)

然而

  • 您的 IDE 厌恶它
  • 所有静态分析工具都讨厌它
  • 没有自动完成
  • 没有类型检查

解决方案

declare(strict_types=1);
// Create class(es) that define(s) those properties
use rfx\Type\Cast;
class Point {
    public int $x;
    public int $y;
}

class Location {
    public string $name;
    public Point $at;
}

function getLocation(): Location {
    // Get your object (from a json source, some external lib, ...).
    // As demonstration we create one here from an array.
    $obj = (object)['name' => 'home', 'at' => ['x' => 4, 'y' => 5]];
    // Cast it (this works recursively, e.g. Location contains a Point object)
    return Cast::as($obj, Location::class);
}

$l = getLocation();

结果

Location Object
(
    [name] => home
    [at] => Point Object
        (
            [x] => 4
            [y] => 5
        )
)
  • 您的 IDE 再次喜欢您
  • 所有静态分析工具将帮助您找到问题
  • 自动完成、类型检查等再次工作

速度

如果性能很重要,并且

  • 您正在转换许多相同类型的对象
  • 所有对象都是浅层的(没有嵌套)
  • 所有属性都是标量类型

那么您可以使用更快的替代方案,其性能与正常构造函数相当

declare(strict_types=1);
// Create a proper class that defines those properties
use rfx\Type\Cast;
class Point {
    public string $name;
    public int $x;
    public int $y;
}

/** @return Point[] */
function getPoints(): array {
    // Get your objects (from a json source, some external lib, ...).
    // As demonstration we create a million from an array.
    $obj = (object)['name' => 'P1', 'x' => 4, 'y' => 5];
    $objs = array_fill(0, 1000000, $obj);
    // Create a factory
    $cf = new Cast(Point::class);
    // Cast them all
    return array_map([$cf, 'cast'], $objs);
}

$p = getPoints();

限制

本节需要编写,并添加一些未来的计划。