{"id":14985640,"url":"https://github.com/nilportugues/php-serializer","last_synced_at":"2025-05-07T04:07:34.354Z","repository":{"id":34560662,"uuid":"38506151","full_name":"nilportugues/php-serializer","owner":"nilportugues","description":"Serialize PHP variables, including objects, in any format. Support to unserialize it too.","archived":false,"fork":false,"pushed_at":"2021-07-26T09:15:09.000Z","size":145,"stargazers_count":51,"open_issues_count":7,"forks_count":19,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-05-07T04:07:26.734Z","etag":null,"topics":["api","array-transformer","data-transformation","hal","hal-api","jsend-transformer","json","json-api","json-transformation","jsonapi","marshaller","php","php7","serialization","transformer","xml","xml-transformation","yaml","yaml-transformer","yml"],"latest_commit_sha":null,"homepage":"http://nilportugues.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-07-03T18:40:05.000Z","updated_at":"2025-04-16T03:48:57.000Z","dependencies_parsed_at":"2022-08-23T16:11:12.329Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/php-serializer","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-serializer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-serializer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-serializer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-serializer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/php-serializer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252810273,"owners_count":21807759,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","array-transformer","data-transformation","hal","hal-api","jsend-transformer","json","json-api","json-transformation","jsonapi","marshaller","php","php7","serialization","transformer","xml","xml-transformation","yaml","yaml-transformer","yml"],"created_at":"2024-09-24T14:11:24.759Z","updated_at":"2025-05-07T04:07:34.329Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","readme":"Serializer for PHP\n=========================\n\n[![Build Status](https://travis-ci.org/nilportugues/php-serializer.svg)](https://travis-ci.org/nilportugues/php-serializer)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/serializer/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/serializer/?branch=master)  [![SensioLabsInsight](https://insight.sensiolabs.com/projects/7ae05bba-985d-4359-8a00-3209f85f1d77/mini.png?)](https://insight.sensiolabs.com/projects/7ae05bba-985d-4359-8a00-3209f85f1d77) \n[![Latest Stable Version](https://poser.pugx.org/nilportugues/serializer/v/stable)](https://packagist.org/packages/nilportugues/serializer) \n[![Total Downloads](https://poser.pugx.org/nilportugues/serializer/downloads)](https://packagist.org/packages/nilportugues/serializer) [![License](https://poser.pugx.org/nilportugues/serializer/license)](https://packagist.org/packages/nilportugues/serializer) \n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n\n- [Installation](#installation)\n- [Introduction](#introduction)\n- [Features](#features)\n- [Serialization](#serialization)\n  - [Serializers (JSON, XML, YAML)](#serializers-json-xml-yaml)\n   - [Example](#example)\n   - [Custom Serializers](#custom-serializers)\n- [Data Transformation](#data-transformation)\n   - [Array Transformer](#array-transformer)\n   - [Flat Array Transformer](#flat-array-transformer) \n   - [XML Transformer](#xml-transformer) \n   - [YAML Transformer](#yaml-transformer) \n   - [JSON Transformer](#json-transformer)\n   - [JSend Transformer](#jsend-transformer)\n   - [JSON API Transformer](#json-api-transformer)\n   - [HAL+JSON Transformer](#haljson-transformer)\n- [Quality](#quality)\n- [Contribute](#contribute)\n- [Author](#author)\n- [License](#license)\n\n## Installation\n\nUse [Composer](https://getcomposer.org) to install the package:\n\n```json\n$ composer require nilportugues/serializer\n```\n\n## Introduction \n\n**What is serialization?**\n\nIn the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment.\n\n    \n**Why not `serialize()` and `unserialize()`?**\n\nThese native functions rely on having the serialized classes loaded and available at runtime and tie your unserialization process to a `PHP` platform.\n\nIf the serialized string contains a reference to a class that cannot be instantiated (e.g. class was renamed, moved namespace, removed or changed to abstract) PHP will immediately die with a fatal error.\n\nIs this a problem? Yes it is. Serialized data is now **unusable**.\n\n## Features\n\n- Serialize to **JSON**, **XML** and **YAML** formats.\n- Serializes **exact copies** of the object provided:\n - **All object properties**, public, protected and private are serialized.\n - All properties from the current object, and all the inherited properties are read and serialized.\n- Handles internal class serialization for objects such as SplFixedArray or classes implementing Traversable.\n- Basic **Data Transformers provided** to convert objects to different output formats.\n- **Production-ready**.\n- **Extensible:** easily write your out `Serializer` format or data `Transformers`.\n\n\n## Serialization\nFor the serializer to work, all you need to do is pass in a PHP Object to the serializer and a Strategy to implement its string representation.\n\n\n### Serializers (JSON, XML, YAML)\n\n- [NilPortugues\\Serializer\\JsonSerializer](https://github.com/nilportugues/serializer/blob/master/src/JsonSerializer.php)\n- [NilPortugues\\Serializer\\XmlSerializer](https://github.com/nilportugues/serializer/blob/master/src/XmlSerializer.php)\n- [NilPortugues\\Serializer\\YamlSerializer](https://github.com/nilportugues/serializer/blob/master/src/YamlSerializer.php)\n\n### Example\n\nIn the following example a `$post` object is serialized into JSON. \n\n**Code**\n\n```php\nuse NilPortugues\\Serializer\\Serializer;\nuse NilPortugues\\Serializer\\Strategy\\JsonStrategy;\n\n//Example object\n$post = new Post(\n  new PostId(9),\n  'Hello World',\n  'Your first post',\n  new User(\n      new UserId(1),\n      'Post Author'\n  ),\n  [\n      new Comment(\n          new CommentId(1000),\n          'Have no fear, sers, your king is safe.',\n          new User(new UserId(2), 'Barristan Selmy'),\n          [\n              'created_at' =\u003e (new DateTime('2015/07/18 12:13:00'))-\u003eformat('c'),\n              'accepted_at' =\u003e (new DateTime('2015/07/19 00:00:00'))-\u003eformat('c'),\n          ]\n      ),\n  ]\n);\n\n//Serialization \n$serializer = new JsonSerializer();\n\n$serializedObject = $serializer-\u003eserialize($post);\n\n//Returns: true\nvar_dump($post == $serializer-\u003eunserialize($serializedObject));\n\necho $serializedObject;\n```\n\nThe object, before it's transformed into an output format, is an array with all the necessary data to be rebuild using unserialize method. \n\n**Output**\n\n```json\n{\n    \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\Post\",\n    \"postId\": {\n        \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\ValueObject\\\\\\\\PostId\",\n        \"postId\": {\n            \"@scalar\": \"integer\",\n            \"@value\": 14\n        }\n    },\n    \"title\": {\n        \"@scalar\": \"string\",\n        \"@value\": \"Hello World\"\n    },\n    \"content\": {\n        \"@scalar\": \"string\",\n        \"@value\": \"Your first post\"\n    },\n    \"author\": {\n        \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\User\",\n        \"userId\": {\n            \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\ValueObject\\\\\\\\UserId\",\n            \"userId\": {\n                \"@scalar\": \"integer\",\n                \"@value\": 1\n            }\n        },\n        \"name\": {\n            \"@scalar\": \"string\",\n            \"@value\": \"Post Author\"\n        }\n    },\n    \"comments\": {\n        \"@map\": \"array\",\n        \"@value\": [\n            {\n                \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\Comment\",\n                \"commentId\": {\n                    \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\ValueObject\\\\\\\\CommentId\",\n                    \"commentId\": {\n                        \"@scalar\": \"integer\",\n                        \"@value\": 1000\n                    }\n                },\n                \"dates\": {\n                    \"@map\": \"array\",\n                    \"@value\": {\n                        \"created_at\": {\n                            \"@scalar\": \"string\",\n                            \"@value\": \"2015-07-18T12:13:00+00:00\"\n                        },\n                        \"accepted_at\": {\n                            \"@scalar\": \"string\",\n                            \"@value\": \"2015-07-19T00:00:00+00:00\"\n                        }\n                    }\n                },\n                \"comment\": {\n                    \"@scalar\": \"string\",\n                    \"@value\": \"Have no fear, sers, your king is safe.\"\n                },\n                \"user\": {\n                    \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\User\",\n                    \"userId\": {\n                        \"@type\": \"Acme\\\\\\\\Domain\\\\\\\\Dummy\\\\\\\\ValueObject\\\\\\\\UserId\",\n                        \"userId\": {\n                            \"@scalar\": \"integer\",\n                            \"@value\": 2\n                        }\n                    },\n                    \"name\": {\n                        \"@scalar\": \"string\",\n                        \"@value\": \"Barristan Selmy\"\n                    }\n                }\n            }\n        ]\n    }\n}'\n```\n\n### Custom Serializers\n\nIf a custom serialization strategy is preferred, the `Serializer` class should be used instead. A `CustomStrategy` must implement the `StrategyInterface`.\n\nUsage is as follows:\n\n```php\nuse NilPortugues\\Serializer\\Serializer;\nuse NilPortugues\\Serializer\\Strategy\\CustomStrategy;\n\n$serializer = new Serializer(new CustomStrategy());\n\necho $serializer-\u003eserialize($post);\n```\n\n----\n\n\n## Data Transformation\n\nTransformer classes **greatly differ** from a `Strategy` class because these cannot `unserialize()` as all class references are lost in the process of transformation. \n\nTo obtain transformations instead of the `Serializer` class usage of `DeepCopySerializer` is required.\n\nThe Serializer library comes with a set of defined Transformers that implement the `StrategyInterface`. \nUsage is as simple as before, pass a Transformer as a `$strategy`. \n\n**For instance:**\n\n```php\n//...same as before ...\n\n$serializer = new DeepCopySerializer(new JsonTransformer());\necho $serializer-\u003eserialize($post);\n```\n\nFollowing, there are some examples and its output, given the `$post` object as data to be Transformed.\n\n### Array Transformer\n\n- [`NilPortugues\\Serializer\\Transformer\\ArrayTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/ArrayTransformer.php)\n\n\n```php\narray(\n  'postId' =\u003e 9,\n  'title' =\u003e 'Hello World',\n  'content' =\u003e 'Your first post',\n  'author' =\u003e array(\n       'userId' =\u003e 1,\n       'name' =\u003e 'Post Author',\n   ),\n  'comments' =\u003e array(\n          0 =\u003e array(\n           'commentId' =\u003e 1000,\n           'dates' =\u003e array(\n              'created_at' =\u003e '2015-07-18T12:13:00+02:00',\n              'accepted_at' =\u003e '2015-07-19T00:00:00+02:00',\n            ),\n           'comment' =\u003e 'Have no fear, sers, your king is safe.',\n           'user' =\u003e array(\n             'userId' =\u003e 2,\n             'name' =\u003e 'Barristan Selmy',\n            ),\n          ),\n      ),\n);\n```\n\n### Flat Array Transformer\n\n- [`NilPortugues\\Serializer\\Transformer\\FlatArrayTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/FlatArrayTransformer.php)\n\n```php\narray(\n  'postId' =\u003e 9,\n  'title' =\u003e 'Hello World',\n  'content' =\u003e 'Your first post',\n  'author.userId' =\u003e 1,\n  'author.name' =\u003e 'Post Author',\n  'comments.0.commentId' =\u003e 1000,\n  'comments.0.dates.created_at' =\u003e '2015-07-18T12:13:00+02:00',\n  'comments.0.dates.accepted_at' =\u003e '2015-07-19T00:00:00+02:00',\n  'comments.0.comment' =\u003e 'Have no fear, sers, your king is safe.',\n  'comments.0.user.userId' =\u003e 2,\n  'comments.0.user.name' =\u003e 'Barristan Selmy',\n);\n```\n\n### XML Transformer\n\n- [`NilPortugues\\Serializer\\Transformer\\XmlTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/XmlTransformer.php)\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cdata\u003e\n  \u003cpostId type=\"integer\"\u003e9\u003c/postId\u003e\n  \u003ctitle type=\"string\"\u003eHello World\u003c/title\u003e\n  \u003ccontent type=\"string\"\u003eYour first post\u003c/content\u003e\n  \u003cauthor\u003e\n    \u003cuserId type=\"integer\"\u003e1\u003c/userId\u003e\n    \u003cname type=\"string\"\u003ePost Author\u003c/name\u003e\n  \u003c/author\u003e\n  \u003ccomments\u003e\n    \u003csequential-item\u003e\n      \u003ccommentId type=\"integer\"\u003e1000\u003c/commentId\u003e\n      \u003cdates\u003e\n        \u003ccreated_at type=\"string\"\u003e2015-07-18T12:13:00+02:00\u003c/created_at\u003e\n        \u003caccepted_at type=\"string\"\u003e2015-07-19T00:00:00+02:00\u003c/accepted_at\u003e\n      \u003c/dates\u003e\n      \u003ccomment type=\"string\"\u003eHave no fear, sers, your king is safe.\u003c/comment\u003e\n      \u003cuser\u003e\n        \u003cuserId type=\"integer\"\u003e2\u003c/userId\u003e\n        \u003cname type=\"string\"\u003eBarristan Selmy\u003c/name\u003e\n      \u003c/user\u003e\n    \u003c/sequential-item\u003e\n  \u003c/comments\u003e\n\u003c/data\u003e\n```\n\n### YAML Transformer\n\n- [`NilPortugues\\Serializer\\Transformer\\YamlTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/YamlTransformer.php)\n\n```yml\ntitle: 'Hello World'\ncontent: 'Your first post'\nauthor:\n    userId: 1\n    name: 'Post Author'\ncomments:\n    - { commentId: 1000, dates: { created_at: '2015-07-18T12:13:00+02:00', accepted_at: '2015-07-19T00:00:00+02:00' }, comment: 'Have no fear, sers, your king is safe.', user: { userId: 2, name: 'Barristan Selmy' } }\n```\n\n\n### Json Transformer\n\nJsonTransformer comes in 2 flavours. For object to JSON transformation the following transformer should be used:\n\n- [`NilPortugues\\Serializer\\Transformer\\JsonTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/JsonTransformer.php)\n\n**Output**\n\n```json\n{\n    \"postId\": 9,\n    \"title\": \"Hello World\",\n    \"content\": \"Your first post\",\n    \"author\": {\n        \"userId\": 1,\n        \"name\": \"Post Author\"\n    },\n    \"comments\": [\n        {\n            \"commentId\": 1000,\n            \"dates\": {\n                \"created_at\": \"2015-07-18T13:34:55+02:00\",\n                \"accepted_at\": \"2015-07-18T14:09:55+02:00\"\n            },\n            \"comment\": \"Have no fear, sers, your king is safe.\",\n            \"user\": {\n                \"userId\": 2,\n                \"name\": \"Barristan Selmy\"\n            }\n        }\n    ]\n}\n``` \n\nIf your desired output is for **API consumption**, you may like to check out the JsonTransformer library, or require it using:\n\n```json\n$ composer require nilportugues/json\n```\n\n\n### JSend Transformer\n\nJSend Transformer has been built to transform data into valid **JSend** specification resources.\n\nPlease check out the [JSend Transformer](https://github.com/nilportugues/jsend-transformer) or download it using:\n\n```json\n$ composer require nilportugues/jsend\n```\n\n\n### JSON API Transformer\n\nJSON API Transformer has been built to transform data into valid **JSON API** specification resources.\n\nPlease check out the [JSON API Transformer](https://github.com/nilportugues/jsonapi-transformer) or download it using:\n\n```json\n$ composer require nilportugues/json-api\n```\n\n\n### HAL+JSON Transformer\n\nHAL+JSON Transformer has been built for **HAL+JSON API creation**. Given an object and a series of mappings a valid HAL+JSON resource representation is given as output.\n\nPlease check out the [HAL+JSON API Transformer](https://github.com/nilportugues/hal-json-transformer) or download it using:\n\n```json\n$ composer require nilportugues/haljson\n```\n\n----\n\n\n## Quality\n\nTo run the PHPUnit tests at the command line, go to the tests directory and issue `phpunit`.\n\nThis library attempts to comply with [PSR-2](http://www.php-fig.org/psr/psr-2/) and [PSR-4](http://www.php-fig.org/psr/psr-4/).\n\nIf you notice compliance oversights, please send a patch via pull request.\n\n## Contribute\n\nContributions to the package are always welcome!\n\n* Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/serializer/issues/new).\n* You can grab the source code at the package's [Git repository](https://github.com/nilportugues/serializer).\n\n## Authors\n\n* [Nil Portugués Calderó](http://nilportugues.com)\n* [The Community Contributors](https://github.com/nilportugues/serializer/graphs/contributors)\n\n## License\nThe code base is licensed under the MIT license.\n","funding_links":["https://paypal.me/nilportugues"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-serializer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Fphp-serializer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-serializer/lists"}