duncan3dc/serial

针对多个后端的一致性序列化助手

2.0.0 2021-07-24 16:50 UTC

This package is auto-updated.

Last update: 2024-08-24 23:35:49 UTC


README

一组具有一致接口的PHP序列化助手。

release build](https://github.com/duncan3dc/serial/actions?query=branch%3Amaster+workflow%3Abuildcheck) coverage

可用类

  • Json(使用原生的json_*函数)
  • Yaml(使用Symfony Yaml组件)
  • Php(使用原生的serialize/unserialize函数)

接口

所有序列化类实现了接口 duncan3dc\Serial\SerialInterface

示例

将数组数据转换为字符串格式

use duncan3dc\Serial\Json;
$data = BusinessLogic::getDataAsArray();
$json = Json::encode($data);

将字符串格式数据转换为数组

use duncan3dc\Serial\Yaml;
$yaml = Api::getYamlResponse($request);
$response = Yaml::decode($yaml);

方便的序列化和存储数据到磁盘的方法

use duncan3dc\Serial\Json;
$filename = "/tmp/file.json";
$data = BusinessLogic::getDataAsArray();
Json::encodeToFile($filename, $data);

从磁盘检索之前存储的数据

use duncan3dc\Serial\Json;
$filename = "/tmp/file.json";
$data = Json::decodeFromFile($filename);

ArrayObject

decode()decodeFromFile() 方法返回一个自定义的 ArrayObject

如果您需要一个普通的数组,您可以通过以下方式获取

$array = Json::decode($jsonString)->asArray();

还有一些辅助方法可以将数据转换为任何可用的序列化格式。

$data = Json::decode($jsonString);
$yaml = $data->asYaml();
$json = $data->asJson();
$php = $data->asPhp();