index.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. ========
  2. Overview
  3. ========
  4. This bundle allows you to easily serialize/unserialize objects. Main features
  5. include:
  6. - able to handle circular references, and object graphs of any depth without
  7. writing a single line of code
  8. - serialize/unserialize objects using annotations to describe metadata
  9. - supports versioning out of the box
  10. - easily customizable as most logic is implemented using clearly defined
  11. interfaces
  12. This bundle works best when you have full control over the objects that you want
  13. to serialize/unserialize as you can leverage the full power of annotations then.
  14. If you want to serialize/deserialize objects provided by third parties, then you
  15. need to write a custom normalizer for these objects.
  16. Installation
  17. ------------
  18. Checkout a copy of the code::
  19. git submodule add https://github.com/schmittjoh/SerializerBundle.git src/JMS/SerializerBundle
  20. Then register the bundle with your kernel::
  21. // in AppKernel::registerBundles()
  22. $bundles = array(
  23. // ...
  24. new JMS\SerializerBundle\JMSSerializerBundle(),
  25. // ...
  26. );
  27. This bundle also requires the Metadata library::
  28. git submodule add https://github.com/schmittjoh/metadata.git vendor/metadata
  29. Make sure that you also register the namespaces with the autoloader::
  30. // app/autoload.php
  31. $loader->registerNamespaces(array(
  32. // ...
  33. 'JMS' => __DIR__.'/../vendor/bundles',
  34. 'Metadata' => __DIR__.'/../vendor/metadata/src',
  35. // ...
  36. ));
  37. Note: You need to use the master branch of the metadata library.
  38. Configuration
  39. -------------
  40. Below is the default configuration, you don't need to change it unless it doesn't
  41. suit your needs::
  42. jms_serializer:
  43. handlers:
  44. datetime:
  45. format: Y-m-dTH:i:s
  46. default_timezone: UTC
  47. array_collection: true
  48. property_naming:
  49. separator: _
  50. lower_case: true
  51. Usage
  52. -----
  53. De-/Serializing Objects
  54. ~~~~~~~~~~~~~~~~~~~~~~~
  55. ::
  56. $serializer = $container->get('serializer');
  57. $serializer->serialize(new MyObject(), 'json');
  58. $serializer->serialize(new MyObject(), 'xml');
  59. The serializer supports JSON, and XML out-of-the-box, and can also handle
  60. many custom XML features (see below).
  61. Versioning
  62. ~~~~~~~~~~
  63. The bundle allows you to have different versions of your objects. This can be
  64. achieved by using the @Since, and @Until annotation which both accept a
  65. standardized PHP version number.
  66. ::
  67. <?php
  68. class VersionedObject
  69. {
  70. /**
  71. * @Until("1.0.x")
  72. */
  73. private $name;
  74. /**
  75. * @Since("1.1")
  76. * @SerializedName("name")
  77. */
  78. private $name2;
  79. }
  80. If you have annotated your objects like above, you can serializing different
  81. versions like this::
  82. <?php
  83. $serializer->setVersion('1.0');
  84. $serializer->serialize(new VersionObject(), 'json');
  85. Defining which properties should be serialized
  86. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  87. The default exclusion policy is to exclude nothing, that is all properties of the
  88. object will be serialized. If you only want to expose a few of the properties,
  89. then it is easier to change the exclusion policy, and only mark these few properties::
  90. <?php
  91. use JMS\SerializerBundle\Annotation\ExclusionPolicy;
  92. use JMS\SerializerBundle\Annotation\Expose;
  93. /**
  94. * The following annotations tells the serializer to skip all properties which
  95. * have not marked with @Expose.
  96. *
  97. * @ExclusionPolicy("all")
  98. */
  99. class MyObject
  100. {
  101. private $foo;
  102. private $bar;
  103. /**
  104. * @Expose
  105. */
  106. private $name;
  107. }
  108. Lifecycle Callbacks
  109. ~~~~~~~~~~~~~~~~~~~
  110. If you need to run some custom logic during the serialization process, you can use
  111. one of these lifecycle callbacks: @PerSerialize, @PostSerialize, or @PostDeserialize
  112. Annotations
  113. -----------
  114. @ExclusionPolicy
  115. ~~~~~~~~~~~~~~~~
  116. This annotation can be defined on a class to indicate the exclusion strategy
  117. that should be used for the class.
  118. +----------+----------------------------------------------------------------+
  119. | Policy | Description |
  120. +==========+================================================================+
  121. | all | all properties are excluded by default; only properties marked |
  122. | | with @Expose will be serialized/unserialized |
  123. +----------+----------------------------------------------------------------+
  124. | none | no properties are excluded by default; all properties except |
  125. | | those marked with @Exclude will be serialized/unserialized |
  126. +----------+----------------------------------------------------------------+
  127. @Exclude
  128. ~~~~~~~~
  129. This annotation can be defined on a property to indicate that the property should
  130. not be serialized/unserialized. Works only in combination with NoneExclusionPolicy.
  131. @Expose
  132. ~~~~~~~
  133. This annotation can be defined on a property to indicate that the property should
  134. be serialized/unserialized. Works only in combination with AllExclusionPolicy.
  135. @SerializedName
  136. ~~~~~~~~~~~~~~~
  137. This annotation can be defined on a property to define the serialized name for a
  138. property. If this is not defined, the property will be translated from camel-case
  139. to a lower-cased underscored name, e.g. camelCase -> camel_case.
  140. @Since
  141. ~~~~~~
  142. This annotation can be defined on a property to specify starting from which
  143. version this property is available. If an earlier version is serialized, then
  144. this property is excluded automatically. The version must be in a format that is
  145. understood by PHP's ``version_compare`` function.
  146. @Until
  147. ~~~~~~
  148. This annotation can be defined on a property to specify until which version this
  149. property was available. If a later version is serialized, then this property is
  150. excluded automatically. The version must be in a format that is understood by
  151. PHP's ``version_compare`` function.
  152. @PreSerialize
  153. ~~~~~~~~~~~~~
  154. This annotation can be defined on a method which is supposed to be called before
  155. the serialization of the object starts.
  156. @PostSerialize
  157. ~~~~~~~~~~~~~~
  158. This annotation can be defined on a method which is then called directly after the
  159. object has been serialized.
  160. @PostDeserialize
  161. ~~~~~~~~~~~~~~~~
  162. This annotation can be defined on a method which is supposed to be called after
  163. the object has been deserialized.
  164. @Type
  165. ~~~~~
  166. This annotation can be defined on a property to specify the type of that property.
  167. This annotation must only be defined when you want to be able to deserialize an
  168. object.
  169. Available Types:
  170. +---------------------------+--------------------------------------------------+
  171. | Type | Description |
  172. +===========================+==================================================+
  173. | boolean | Primitive boolean |
  174. +---------------------------+--------------------------------------------------+
  175. | integer | Primitive integer |
  176. +---------------------------+--------------------------------------------------+
  177. | double | Primitive double |
  178. +---------------------------+--------------------------------------------------+
  179. | string | Primitive string |
  180. +---------------------------+--------------------------------------------------+
  181. | array | An array with arbitrary keys, and values. |
  182. +---------------------------+--------------------------------------------------+
  183. | array<T> | A list of type T (T can be any available type). |
  184. | | Examples: |
  185. | | array<string>, array<MyNamespace\MyObject>, etc. |
  186. +---------------------------+--------------------------------------------------+
  187. | array<K, V> | A map of keys of type K to values of type V. |
  188. | | Examples: array<string, string>, |
  189. | | array<string, MyNamespace\MyObject>, etc. |
  190. +---------------------------+--------------------------------------------------+
  191. | DateTime | PHP's DateTime object |
  192. +---------------------------+--------------------------------------------------+
  193. | T | Where T is a fully qualified class name. |
  194. +---------------------------+--------------------------------------------------+
  195. | ArrayCollection<T> | Similar to array<T>, but will be deserialized |
  196. | | into Doctrine's ArrayCollection class. |
  197. +---------------------------+--------------------------------------------------+
  198. | ArrayCollection<K, V> | Similar to array<K, V>, but will be deserialized |
  199. | | into Doctrine's ArrayCollection class. |
  200. +---------------------------+--------------------------------------------------+
  201. Examples::
  202. <?php
  203. namespace MyNamespace;
  204. use JMS\SerializerBundle\Annotation\Type;
  205. class BlogPost
  206. {
  207. /**
  208. * @Type("ArrayCollection<MyNamespace\Comment>")
  209. */
  210. private $comments;
  211. /**
  212. * @Type("string")
  213. */
  214. private $title;
  215. /**
  216. * @Type("MyNamespace\Author")
  217. */
  218. private $author;
  219. /**
  220. * @Type("DateTime")
  221. */
  222. private $createdAt;
  223. /**
  224. * @Type("boolean")
  225. */
  226. private $published;
  227. /**
  228. * @Type("array<string, string>")
  229. */
  230. private $keyValueStore;
  231. }
  232. @XmlRoot
  233. ~~~~~~~~
  234. This allows you to specify the name of the top-level element.
  235. ::
  236. <?php
  237. use JMS\SerializerBundle\Annotation\XmlRoot;
  238. /** @XmlRoot("user") */
  239. class User
  240. {
  241. private $name = 'Johannes';
  242. }
  243. Resulting XML::
  244. <user>
  245. <name><![CDATA[Johannes]]></name>
  246. </user>
  247. @XmlAttribute
  248. ~~~~~~~~~~~~~
  249. This allows you to mark properties which should be set as attributes,
  250. and not as child elements.
  251. ::
  252. <?php
  253. use JMS\SerializerBundle\Annotation\XmlAttribute;
  254. class User
  255. {
  256. /** @XmlAttribute */
  257. private $id = 1;
  258. private $name = 'Johannes';
  259. }
  260. Resulting XML::
  261. <result id="1">
  262. <name><![CDATA[Johannes]]></name>
  263. </result>
  264. @XmlList
  265. ~~~~~~~~
  266. This allows you to define several properties of how arrays should be
  267. serialized. This is very similar to @XmlMap, and should be used if the
  268. keys of the array are not important.
  269. ::
  270. <?php
  271. use JMS\SerializerBundle\Annotation\XmlList;
  272. use JMS\SerializerBundle\Annotation\XmlRoot;
  273. /** @XmlRoot("post") */
  274. class Post
  275. {
  276. /**
  277. * @XmlList(inline = true, entry = "comment")
  278. */
  279. private $comments = array(
  280. new Comment('Foo'),
  281. new Comment('Bar'),
  282. );
  283. }
  284. class Comment
  285. {
  286. private $text;
  287. public function __construct($text)
  288. {
  289. $this->text = $text;
  290. }
  291. }
  292. Resulting XML::
  293. <post>
  294. <comment>
  295. <text><![CDATA[Foo]]></text>
  296. </comment>
  297. <comment>
  298. <text><![CDATA[Bar]]></text>
  299. </comment>
  300. </post>
  301. @XmlMap
  302. ~~~~~~~
  303. Similar to @XmlList, but the keys of the array are meaningful.