laminas/laminas-serializer
Serialize and deserialize PHP data using multiple adapters (e.g., PHP native, JSON, XML, WDDX) with consistent options, error handling, and extensibility. Useful for caching, sessions, message payloads, and storage across different formats.
Start by installing the package via Composer:
composer require laminas/laminas-serializer
Then, create a serializer instance with your preferred adapter. The most common choice is Json for interoperability (especially in APIs), or PhpSerialized for performance in internal storage (e.g., caching):
use Laminas\Serializer\Serializer;
// For JSON (safe for API payloads and cross-language compatibility)
$serializer = new Serializer(Serializer::ADAPTER_JSON);
// For PHP-specific serialization (e.g., Redis cache, internal storage)
$serializer = new Serializer(Serializer::ADAPTER_PHP_SERIALIZE);
Your first use case? Storing complex PHP arrays or objects in a cache:
$data = ['user' => 'alice', 'permissions' => ['read', 'write']];
$cache->save($serializer->serialize($data), 'user_perms_alice');
SerializerInterface as a dependency (e.g., via a factory) to keep your code decoupled from the underlying format. Configure the adapter in config/autoload/serializer.global.php.serialize()/unserialize() manually.Json adapter for APIs, but always set Json::encodeOptions to exclude JSON_PRESERVE_ZERO_FRACTION and include JSON_THROW_ON_ERROR (if using laminas/laminas-serializer ≥ v2.18):
$serializer = new Serializer(Serializer::ADAPTER_JSON, [
'adapterOptions' => [
'encodeOptions' => JSON_THROW_ON_ERROR,
],
]);
Laminas\Serializer\Adapter\AdapterInterface for niche needs (e.g., Protocol Buffers, MessagePack). Register via the AdapterManager or directly instantiate with setAdapter().Igbinary requires manual installation. Don’t assume it’s available—catch RuntimeException on instantiation or fallback gracefully.PhpSerialized stores stdClass and internal class names. If you unmarshal into different class versions (e.g., after refactor), you’ll get __PHP_Incomplete_Class. Prefer Json for long-lived storage or microservice boundaries.unserialize(). The package mitigates this somewhat via exceptions, but always validate or decode via Json for public-facing endpoints.[] (JSON), but with PhpSerialized, empty arrays are a:0:{}—watch for this in cache key collisions or diff tools.Laminas\Serializer\Exception\RuntimeException for format errors (e.g., corrupted cache entries) and Laminas\Serializer\Exception\LogicException for misconfiguration (e.g., unsupported adapter name). Log the raw payload in dev environments for debugging.serialize()-compatible adapters for objects with __serialize() if you need strict type fidelity—PhpSerialized adapter preserves __sleep()/__wakeup() semantics, but JSON loses class identity by design.How can I help you explore Laravel packages today?