harp-orm / serializer
序列化对象属性
0.1.1
2014-07-17 11:30 UTC
This package is auto-updated.
Last update: 2024-09-21 21:39:53 UTC
README
序列化对象/数组属性,每个属性使用不同的规则。
用法
use Harp\Serializer; $serializers = new Serializer\Serializers([ new Serializer\Native('nativeSerializerdArray'), new Serializer\Csv('csvString'), new Serializer\Json('jsonProperty'), ]); $obj = new stdClass(); $obj->nativeSerializerdArray = array('test' => 'param'); $obj->csvString = array('val', 'val2'); $obj->jsonProperty = array('test' => 'asd'); $serializers->serialize($obj); // Will output: // stdClass Object // ( // [nativeSerializerdArray] => a:1:{s:4:"test";s:5:"param";} // [csvString] => val,val2 // [jsonProperty] => {"test":"asd"} // ) print_r($obj); // Will unserialize all the relevant properties $serializers->unserialize($obj);
对象序列化
如果你有一个实现Serializable接口的对象,但没有使用原生php序列化,你可以使用对象序列化器,这可以大大减少对象的字符串占用。
use Serializable; class SimpleObject implements Serializable { public $prop1; public $prop2; public function serialize() { return $this->prop1.','.$this->prop2; } public function unserialize($data) { list($this->prop1, $this->prop2) = explode(',', $data); } } $serializers = new Serializer\Serializers([ new Serializer\Object('test', 'SimpleObject'), ]); $obj = new stdClass(); $obj->test = new SimpleObject(); $obj->test->prop1 = 10; $obj->test->prop2 = 20; $serializers->serialize($obj); // Will output: // stdClass Object // ( // [test] => 10,20 // ) print_r($obj); // Will unserialize all the relevant properties $serializers->unserialize($obj);
Harp ORM 集成
序列化器集成到 Harp ORM 中,允许你通过序列化模型属性在数据库中存储任意数据。
例如,可以在 "response" 字段中存储 api 响应。
// Model class Payment extends AbstractModel { public $id; public $response; } // Repo class Payment extends AbstractRepo { public function initialize() { $this ->addSerializers([ new Serializer\Json('response'), ]); } } $model = new Model\Payment(['response' => $someArray]); // The response property will get serialized as a json string. Repo\Payment::get()->save($model);
SerializersTrait
这个特质允许你轻松地向另一个对象添加序列化器。
class TestConfig { use SerializersTrait; } $config = new TestConfig(); $config ->serializeCsv('name'); // Return the Asserts object $config->getSerializers();
以下是该特质添加的所有方法。
许可协议
版权 (c) 2014, Clippings Ltd. 由 Ivan Kerin 开发
根据 BSD-3-Clause 许可协议,请阅读 LICENSE 文件。