JsonCodec
JsonCodec is a PHP library that builds on top of PHP's native JsonSerializable
interface. It is used to implement JSON serialization and deserialization for custom objects. It was introduced into MediaWiki 1.36 via Gerrit change 641575.
Install
To use the package outside of MediaWiki, install the wikimedia/json-codec package from Packagist:
composer require wikimedia/json-codec
Usage
<?php
use Wikimedia\JsonCodec\JsonCodecable;
use Wikimedia\JsonCodec\JsonCodecableTrait;
class SampleObject implements JsonCodecable {
use JsonCodecableTrait;
/** @var string */
public string $property;
// ....
// Implement JsonCodecable using the JsonCodecableTrait
/** @inheritDoc */
public function toJsonArray(): array {
return [
'property' => $this->property,
];
}
/** @inheritDoc */
public static function newFromJsonArray( array $json ): SampleObject {
return new SampleObject( $json['property'] );
}
}
For more examples, you can read the library's README.md.