harm-less / php-encoder
智能编码器,可将整个PHP对象转换为Json或XML,例如。
0.3.0
2016-05-08 21:19 UTC
Requires
- php: >=5.3.0
- openlss/lib-array2xml: ~0.0.9
Requires (Dev)
- phpunit/php-code-coverage: 2.x
- phpunit/phpunit: 4.5.*
README
php-encoder 是一个快速灵活的PHP 5.3+编码器
关于
此库允许您以XML或JSON(编码)等不同格式保存PHP对象的快照。当您的项目设置正确后,您可以通过解码来重复使用快照。解码过程将返回与您开始时相同的PHP对象。
如果您想快速找到保存PHP对象状态的方法,此库对您很有用。例如,考虑一个允许您以各种方式自定义特定产品的配置器。
入门
- 需要PHP 5.3.x
- 使用 Composer (推荐)或手动安装 php-encoder
- 设置您的PHP对象所需的节点
Composer 安装
- 获取 Composer
- 使用
composer require harm-less/php-encoder
需求编码器 - 将以下内容添加到应用程序的主要PHP文件中:
require 'vendor/autoload.php';
包含的编码器
目前有2种编码类型可用:XML 和 JSON。只要您正确设置了节点,它们可以互换使用。
示例
Hello World - 强制性的Hello World示例
<?php require('vendor/autoload.php'); use PE\Encoders\XmlEncoder; use PE\Nodes\EncoderNode; use PE\Nodes\EncoderNodeVariable; // create a simple class with 1 variable and a setter/getter class HelloWorld { private $foo; public function setFoo($value) { $this->foo = $value; } public function getFoo() { return $this->foo; } } // create a corresponding node and add the variable class HelloWorldNode extends EncoderNode { function __construct() { parent::__construct('hello-worlds', 'hello-world', null); $this->addVariable(new EncoderNodeVariable('foo')); } } // register the node so it becomes known to the encoder EncoderNode::addNode(new HelloWorldNode()); // create a HelloWorld object $helloWorld = new HelloWorld(); $helloWorld->setFoo('hello world'); // make an instance of an encoder type and encode the object $encoder = new XmlEncoder(); $encodedResultXml = $encoder->encode($helloWorld); // will output: /* <?xml version="1.0" encoding="UTF-8"?> * <encoded> * <hello-world foo="hello world"/> * </encoded> */ echo htmlentities($encodedResultXml->saveXML()); // decode the XML again $decoded = $encoder->decode($encodedResultXml->saveXML()); // will output: /* * HelloWorld Object * ( * [foo:HelloWorld:private] => hello world * ) */ print_r($decoded['hello-world']); ?>
单元测试
此项目使用 PHPUnit 作为其单元测试框架。
所有测试都位于 /tests
中,每个测试都扩展了一个抽象类 AbstractPETest
要测试项目,请简单运行 composer install --dev
以使用Composer下载PHPUnit的通用版本,然后从主目录运行测试 phpunit
或 ./vendor/bin/phpunit