PHP code example of horde / pack

1. Go to this page and download the library: Download horde/pack library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

horde / pack example snippets


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),
);

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,
);

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),
        );
    }
}

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(),
    ),
);