Sorry, we don't support your browser.  Install a modern browser

Add msg_pack and igbinary support to caches

adding both msg_pack and igbinary support to the existing Cache\Value boils down to adding a few if-clauses.
the benefit of both of these is that they are 2x faster on deserialization (major usecase of caches) and a tiny bit faster and in case of msg_pack smaller than JSON serialization.

and example from my upcoming Turbo plugin

<?php

namespace Bnomei;

use Kirby\Cache\Value;

class TurboValue extends Value
{
    public function toJson(): string
    {
        if (extension_loaded('msgpack')) {
            return msgpack_pack($this->toArray()); // @phpstan-ignore-line
        }

        if (extension_loaded('igbinary')) {
            return igbinary_serialize($this->toArray()) ?: '';
        }

        return parent::toJson();
    }

    public static function fromJson(string $json): ?static
    {
        if (extension_loaded('msgpack')) {
            $data = msgpack_unpack($json); // @phpstan-ignore-line
            if (is_array($data)) {
                return parent::fromArray($data);
            }
        }

        if (extension_loaded('igbinary')) {
            $data = igbinary_unserialize($json);
            if (is_array($data)) {
                return parent::fromArray($data);
            }
        }

        return parent::fromJson($json);
    }
}
a year ago

This does throw an error in our unit tests. Do you know why that could be?

igbinary_unserialize_header: unsupported version: "{\"cr"..., should begin with a binary version header of ... (Nolt doesn’t let me post the full error message).

(Kirby\Cache\ValueTest::testJsonConversion)

5 months ago
5 months ago

Oh yes very likely a stored value from our regular format. We would need a way to recognize the format before unserializing it. Otherwise existing setups will break.

5 months ago

maybe a dynamic cache prefix for each?

5 months ago

Since JSON always starts with { and igbinary doesn’t, shouldn’t a check for the first character already be enough?

5 months ago

or a postfix on the file extension?
.msgpack.cache .igbinary.cache

(edited: better to end with .cache)

5 months ago

@Bruno Meilick Since this is in the Value class, it might get stored in any kind of cache, not necessarily a file cache. So I think we would need to detect it from the value/content itself.

5 months ago

great idea

5 months ago