定制 horde/pack 二次开发

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

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

horde/pack

Composer 安装命令:

composer require horde/pack

包简介

Data packing library

README 文档

README

Data packing library that picks the fastest serialization format your PHP installation supports for each value, then optionally compresses the result.

A drop-in replacement for serialize()/json_encode() for cache, session and inter-process payloads. Pack autodetects whether the input contains real PHP objects and chooses a driver that can round- trip it. Compression is on by default for payloads above a configurable size threshold.

Installation

composer require horde/pack

Optional extensions, in priority order (Pack works without any of them but smaller and faster ones come from native code):

  • ext-msgpack. Highest priority for plain data (scalars, arrays).
  • ext-igbinary. High priority for payloads containing real PHP objects.
  • ext-json. Always available with PHP since 8.0. Second-priority for plain data.
  • PHP serialize(). Always available. Universal fallback.

Two implementations side by side

The 2.x line ships two parallel implementations in one Composer package:

  • Modern PSR-4 under Horde\Pack\ in src/. Use this for new code.
  • Legacy PSR-0 under Horde_Pack in lib/. Existing callers keep working unchanged.

Both implementations share one wire format: a value packed by either class unpacks under the other. See doc/wire-format.md for the on-disk specification. They cohabit in caches and session blobs without coordination.

The legacy classes are in maintenance mode: bug fixes land if reported, but no new features. New work should target Horde\Pack\Packer.

Quick start (modern API)

use Horde\Pack\Packer;
use Horde\Pack\PackOptions;

$packer = new Packer();

// Round-trip a value.
$blob = $packer->pack(['cache_key' => 'some data']);
$value = $packer->unpack($blob);

// Disable compression for short or already-compressed inputs.
$blob = $packer->pack($payload, PackOptions::uncompressed());

// Restrict object deserialization to a class whitelist (security).
$value = $packer->unpack(
    $blob,
    (new PackOptions())->withAllowedClasses(MyDto::class),
);

Configuring the packer

Constructor parameters are typed and have sensible defaults:

use Horde\Pack\DefaultDriverRegistry;
use Horde\Pack\DefaultCompressor;
use Horde\Pack\Driver\Json;
use Horde\Pack\Driver\Serialize;
use Horde\Pack\Packer;

// Default: every shipped driver supported by the host, fast compressor.
$packer = new Packer();

// Restricted driver set: only Json and Serialize.
$packer = new Packer(
    new DefaultDriverRegistry(new Json(), new Serialize()),
);

// Custom compressor (must implement Horde\Pack\Compressor).
$packer = new Packer(
    new DefaultDriverRegistry(),
    $myCompressor,
);

Per-call options

PackOptions is an immutable value object with named constructors and with*() builders:

Factory / builder Effect
PackOptions::compressed($threshold = 128) Compress payloads larger than threshold (the default).
PackOptions::uncompressed() Never compress.
PackOptions::alwaysCompress() Compress every payload regardless of size.
withAllowedDrivers(string ...$classes) Restrict to listed driver classes.
withAllowedClasses(string ...$classes) Restrict object deserialization to listed classes. Empty list disables object deserialization entirely.
withPhpObjects(bool) Skip the autodetect scan and assert whether input contains real PHP objects.

Security: allowedClasses

Driver\Serialize::unpack() honours an allowed_classes whitelist when deserializing PHP objects. Tightening this whitelist closes a deserialization-gadget primitive that an attacker who can corrupt the cache otherwise has access to.

The library default is null (unrestricted) for backwards compatibility with the legacy Horde_Pack. Application factories that wrap Packer are the right layer to apply default-deny:

final class HardenedPackerFactory
{
    public static function create(): Packer
    {
        return new Packer();
    }

    public static function safelyUnpack(Packer $packer, string $blob): mixed
    {
        return $packer->unpack(
            $blob,
            (new PackOptions())->withAllowedClasses(MyAllowedDto::class),
        );
    }
}

The other shipped drivers (Json, Igbinary, Msgpack, MsgpackSerialize) do not honour allowedClasses. Json refuses to encode non-stdClass objects in the first place, so the whitelist is moot there. The msgpack and igbinary extensions provide no class-whitelist hook in their deserializers. The option is accepted for interface compatibility but ignored. Callers who need a hard whitelist must restrict the driver set to Serialize only via withAllowedDrivers().

Custom drivers

Implement Horde\Pack\Driver and register your driver against an unused wire-format slot. The canonical drivers occupy slots 1, 2, 4, 8 and 16. Slot 32 is reserved for third-party drivers in the canonical registry layout.

use Horde\Pack\Driver;
use Horde\Pack\WireFormat;

final class CborDriver implements Driver
{
    public function id(): int { return 32; }
    public function supportsPhpObjects(): bool { return false; }
    public function supported(): bool { return extension_loaded('cbor'); }
    public function pack(mixed $data): string { /* ... */ }
    public function unpack(string $data, ?array $allowedClasses = null): mixed { /* ... */ }
}

$packer = new Packer(
    new DefaultDriverRegistry(
        new CborDriver(),
        new Driver\Serialize(),
        new Driver\Json(),
    ),
);

DefaultDriverRegistry's variadic constructor REPLACES the canonical driver set entirely when called with arguments. Pass the canonical drivers explicitly alongside your own if you want to extend rather than replace.

See also

License

LGPL 2.1. See LICENSE.

horde/pack 适用场景与选型建议

horde/pack 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.74k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 10 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 1
  • Watchers: 5
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-2.1-only
  • 更新时间: 2023-10-26