定制 krak/marshal 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

krak/marshal

Composer 安装命令:

composer require krak/marshal

包简介

Data marshal and transformation library

README 文档

README

A library for marshaling data with a functional design. This is useful for transforming/marshaling data for API output, un-marshaling and hydrating serialized data, or for any other types types of transforming.

Usage

<?php

use Krak\Marshal as m;

$users = getUsers(); // get users from an orm or something

$m = m\map(function($user)
{
    return m\merge([
        m\keys(['id', 'first_name', 'last_name']),
        function($user) {
            return [
                'like_count' => (int) $user->like_count,
                'biography' => substr($user->biography, 0, 64),
                'created_at_ts' => $user->created_at->getTimestamp(),
            ];
        }
    ]);
});

$marshaled = $m($users);

/*
[
    [
        'id' => ...,
        'first_name' => ...,
        'last_name' => ...,
        'biography' => ...,
        'created_at_ts' => ...,
    ],
    ...
]
*/

Accessors

For certain marshalers, you'll want to marshal an entity in the form of the array or object. For that, we have accessors. An accessor implements the Krak\Marshal\Access interface.

<?php

interface Access {
    public function get($data, $key, $default = null);
    public function has($data, $key);
}

usage:

<?php

$access = new Krak\Marshal\ArrayKeyAccess();
$data = ['a' => 1];
$access->has($data, 'a'); // true
$access->has($data, 'b'); // false
$access->get($data, 'a'); // 1
$access->get($data, 'b', 0); // 0

Hydrators

Hydrators are used to marshal array data into an object. Each hydrator is any callable with the following interface

<?php

interface Hydrator {
    public function __invoke($class, $data);
}
<?php

class MyClass {
    public $a;
    public $b;
}

$hydrate = publicPropertyHydrator();
$obj = $hydrate(new MyClass(), [
    'a' => 1,
    'b' => 2,
]);

// $obj now is hydrated with those values

API

hydrate($class, $hydrator = null)

Creates a marshaler that will hydrate the data with the given $class parameter and forwards the $class and the $data from the marshaler to the $hydrator. If no hydrator is supplied, the default hydrator() will be used.

<?php

class MyClass {
    public $a;
}

$marshal = Krak\Marshal\hydrate(MyClass::class);
$obj = $marshal(['a' => 1]);
assert($obj instanceof MyClass);

keyMap($map)

transforms the keys of the data into a new key

rename(array $map)

renames key fields into a new name

only(array $fields)

It only includes the given fields. Everything else is filtered out.

except(array $fields)

It includes all except the given fields. Everything else is kept.

filter(callable $filter)

Filters the collection via the filter func which has the signature $filter($value, $key): bool

dates($format = 'r')

Formats all instances of DateTimeInterface with the given format specifier.

objectVars()

Converts the properties of an object into an array. This is just an alias of get_object_vars.

typeCast(array $fields, $type)

Type casts the given fields into a specific type.

pipe($marshalers)

Creates a marshaler that pipes the result of one marshaler into the next marshaler

<?php

$m = pipe([camelizeKeys(), keys(['id', 'firstName'])]);
$m(['id' => 1, 'first_name' => 2]);

merge($marshalers)

Creates a marshaler that will apply $marshalers onto a value and then merges all of the results with array_merge. This expects the $marshalers to return arrays.

keys($fields, Access $acc = null)

Creates a marshaler that retuns the fields of the data

map($marshaler)

Creates a marshaler which takes a collection and returns an array of each of the marshaled items

collection($marshalers, Access $acc = null)

Creates a marshaler of a collection based off of the collection of marshalers passed in. Each $marshaler in $key => $marshaler will marshal each $value in $key => $value based on the $key.

on($marshalers, Access $acc = null)

Similar to collection, it marshals the fields of the collection based off of the map of marshalers passed in. The only difference is that it updates the fields in the original collection and returns the entire modified collection.

stringyKeys($cb)

Maps a key by allowing a stringy instance passed to callback for key manipulation

underscoredKeys()

Converts the keys to underscore style keys using the Stringy::underscored function

camelizeKeys()

Converts the keys to camelCase style keys using the Stringy::camelize function

identity()

Creates a marshaler for the identity function

mock($val)

Creates a marshaler that returns $val always. This is useful for testing

notnull($marshaler)

Creates a marshaler that will not allow null values to be passed to the marshaler. if a null value is passed, it just returns null and doesn't call the marshaler

hydrator()

Returns a statically cached instance of a default hydrator instance.

classNameHydrator($hydrator)

Treats the $class parameter as a class name and will instantiate a class and delgate to the internal hydrator

publicPropertyHydrator()

Assigns the properties from array into the $class object passed in via publicly accessible properties.

fromXML()

Parses XML string into an array.

<?php

$xml = <<<XML
<?xml version="1.0" ?>
<root a="1">
    <item>Value</item>
    <items>
        <item>1</item>
        <item>2</item>
    </items>
    <map id="1">
        <a>A</a>
        <b>B</b>
    </map>
    <node>
        <![CDATA[<cdata>]]>
    </node>
</root>
XML;
$unmarshal = Krak\Marshal\fromXML();
var_dump($unmarshal($xml));
/** Outputs:
array(5) {
  ["@a"]=>
  string(1) "1"
  ["item"]=>
  string(5) "Value"
  ["items"]=>
  array(1) {
    ["item"]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(1) "2"
    }
  }
  ["map"]=>
  array(3) {
    ["@id"]=>
    string(1) "1"
    ["a"]=>
    string(1) "A"
    ["b"]=>
    string(1) "B"
  }
  ["node"]=>
  string(7) "<cdata>"
}
*/

class ArrayKeyAccess

Performs access on arrays via the key.

class ObjectPropertyAccess

Performs access on object properties via the property name

class AnyAccess

Delegates access to either ArrayKeyAccess or ObjectPropertyAccess if the data is an array or not.

This is the default accessor used.

access()

Returns a statically cached instance of AnyAccess

krak/marshal 适用场景与选型建议

krak/marshal 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.44k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2015 年 07 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「transformer」 「Marshal」 「marshaler」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 krak/marshal 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 krak/marshal 我们能提供哪些服务?
定制开发 / 二次开发

基于 krak/marshal 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.44k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 16
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-07-06