rfx/cast
Composer 安装命令:
composer require rfx/cast
包简介
Cast / convert a stdClass or any other class to another class
README 文档
README
ABOUT
Allows you to cast a stdClass (or any other class) to some other class.
INSTALL
composer require rfx/cast
USAGE
Problem
So you received a beautiful object that you want to use
stdClass Object
(
[name] => home
[at] => stdClass Object
(
[x] => 4
[y] => 5
)
)
However:
- Your IDE hates it
- All static analysis tools hate it
- No autocompletion
- No type checks
Solution
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();
Result
Location Object
(
[name] => home
[at] => Point Object
(
[x] => 4
[y] => 5
)
)
- Your IDE loves you again
- All static analysis tools will help you find problems
- Autocompletion, type checks, etc. work again
Speed
If performance is important and:
- you are casting many objects of the same type
- all your objects are shallow (no nesting)
- all the properties are scalar types
then you can use the faster alternative, which is as performant as a normal constructor:
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();
LIMITATIONS
This section needs to be written, and some future plans added.
rfx/cast 适用场景与选型建议
rfx/cast 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 83 次下载、GitHub Stars 达 1, 最近一次更新时间为 2022 年 05 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 rfx/cast 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 rfx/cast 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 83
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: LGPL-2.1-only
- 更新时间: 2022-05-16