index.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. - can be configured via annotations, YAML, XML, or PHP
  13. Installation
  14. ------------
  15. Checkout a copy of the code::
  16. git submodule add https://github.com/schmittjoh/JMSSerializerBundle.git src/JMS/SerializerBundle
  17. Then register the bundle with your kernel::
  18. // in AppKernel::registerBundles()
  19. $bundles = array(
  20. // ...
  21. new JMS\SerializerBundle\JMSSerializerBundle(),
  22. // ...
  23. );
  24. This bundle also requires the Metadata library::
  25. git submodule add https://github.com/schmittjoh/metadata.git vendor/metadata
  26. Make sure that you also register the namespaces with the autoloader::
  27. // app/autoload.php
  28. $loader->registerNamespaces(array(
  29. // ...
  30. 'JMS' => __DIR__.'/../vendor/bundles',
  31. 'Metadata' => __DIR__.'/../vendor/metadata/src',
  32. // ...
  33. ));
  34. Note: You need to use the master branch of the metadata library.
  35. Configuration
  36. -------------
  37. Below is the default configuration, you don't need to change it unless it doesn't
  38. suit your needs::
  39. jms_serializer:
  40. handlers:
  41. object_based: false
  42. datetime:
  43. format: Y-m-dTH:i:s
  44. default_timezone: UTC
  45. array_collection: true
  46. form_error: true
  47. constraint_violation: true
  48. property_naming:
  49. separator: _
  50. lower_case: true
  51. metadata:
  52. cache: file
  53. debug: %kernel.debug%
  54. file_cache:
  55. dir: %kernel.cache_dir%/serializer
  56. # Using auto-detection, the mapping files for each bundle will be
  57. # expected in the Resources/config/serializer directory.
  58. #
  59. # Example:
  60. # class: My\FooBundle\Entity\User
  61. # expected path: @MyFooBundle/Resources/config/serializer/Entity.User.(yml|xml|php)
  62. auto_detection: true
  63. # if you don't want to use auto-detection, you can also define the
  64. # namespace prefix and the corresponding directory explicitly
  65. directories:
  66. any-name:
  67. namespace_prefix: My\FooBundle
  68. path: @MyFooBundle/Resources/config/serializer
  69. another-name:
  70. namespace_prefix: My\BarBundle
  71. path: @MyBarBundle/Resources/config/serializer
  72. Usage
  73. -----
  74. De-/Serializing Objects
  75. ~~~~~~~~~~~~~~~~~~~~~~~
  76. ::
  77. $serializer = $container->get('serializer');
  78. $serializer->serialize(new MyObject(), 'json');
  79. $serializer->serialize(new MyObject(), 'xml');
  80. The serializer supports JSON, and XML out-of-the-box, and can also handle
  81. many custom XML features (see below).
  82. Versioning
  83. ~~~~~~~~~~
  84. The bundle allows you to have different versions of your objects. This can be
  85. achieved by using the @Since, and @Until annotation which both accept a
  86. standardized PHP version number.
  87. ::
  88. <?php
  89. class VersionedObject
  90. {
  91. /**
  92. * @Until("1.0.x")
  93. */
  94. private $name;
  95. /**
  96. * @Since("1.1")
  97. * @SerializedName("name")
  98. */
  99. private $name2;
  100. }
  101. If you have annotated your objects like above, you can serializing different
  102. versions like this::
  103. <?php
  104. $serializer->setVersion('1.0');
  105. $serializer->serialize(new VersionObject(), 'json');
  106. Defining which properties should be serialized
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. The default exclusion policy is to exclude nothing, that is all properties of the
  109. object will be serialized. If you only want to expose a few of the properties,
  110. then it is easier to change the exclusion policy, and only mark these few properties::
  111. <?php
  112. use JMS\SerializerBundle\Annotation\ExclusionPolicy;
  113. use JMS\SerializerBundle\Annotation\Expose;
  114. /**
  115. * The following annotations tells the serializer to skip all properties which
  116. * have not marked with @Expose.
  117. *
  118. * @ExclusionPolicy("all")
  119. */
  120. class MyObject
  121. {
  122. private $foo;
  123. private $bar;
  124. /**
  125. * @Expose
  126. */
  127. private $name;
  128. }
  129. Lifecycle Callbacks
  130. ~~~~~~~~~~~~~~~~~~~
  131. If you need to run some custom logic during the serialization process, you can use
  132. one of these lifecycle callbacks: @PreSerialize, @PostSerialize, or @PostDeserialize
  133. Annotations
  134. -----------
  135. @ExclusionPolicy
  136. ~~~~~~~~~~~~~~~~
  137. This annotation can be defined on a class to indicate the exclusion strategy
  138. that should be used for the class.
  139. +----------+----------------------------------------------------------------+
  140. | Policy | Description |
  141. +==========+================================================================+
  142. | all | all properties are excluded by default; only properties marked |
  143. | | with @Expose will be serialized/unserialized |
  144. +----------+----------------------------------------------------------------+
  145. | none | no properties are excluded by default; all properties except |
  146. | | those marked with @Exclude will be serialized/unserialized |
  147. +----------+----------------------------------------------------------------+
  148. @Exclude
  149. ~~~~~~~~
  150. This annotation can be defined on a property to indicate that the property should
  151. not be serialized/unserialized. Works only in combination with NoneExclusionPolicy.
  152. @Expose
  153. ~~~~~~~
  154. This annotation can be defined on a property to indicate that the property should
  155. be serialized/unserialized. Works only in combination with AllExclusionPolicy.
  156. @SerializedName
  157. ~~~~~~~~~~~~~~~
  158. This annotation can be defined on a property to define the serialized name for a
  159. property. If this is not defined, the property will be translated from camel-case
  160. to a lower-cased underscored name, e.g. camelCase -> camel_case.
  161. @Since
  162. ~~~~~~
  163. This annotation can be defined on a property to specify starting from which
  164. version this property is available. If an earlier version is serialized, then
  165. this property is excluded automatically. The version must be in a format that is
  166. understood by PHP's ``version_compare`` function.
  167. @Until
  168. ~~~~~~
  169. This annotation can be defined on a property to specify until which version this
  170. property was available. If a later version is serialized, then this property is
  171. excluded automatically. The version must be in a format that is understood by
  172. PHP's ``version_compare`` function.
  173. @PreSerialize
  174. ~~~~~~~~~~~~~
  175. This annotation can be defined on a method which is supposed to be called before
  176. the serialization of the object starts.
  177. @PostSerialize
  178. ~~~~~~~~~~~~~~
  179. This annotation can be defined on a method which is then called directly after the
  180. object has been serialized.
  181. @PostDeserialize
  182. ~~~~~~~~~~~~~~~~
  183. This annotation can be defined on a method which is supposed to be called after
  184. the object has been deserialized.
  185. @Type
  186. ~~~~~
  187. This annotation can be defined on a property to specify the type of that property.
  188. This annotation must only be defined when you want to be able to deserialize an
  189. object.
  190. Available Types:
  191. +---------------------------+--------------------------------------------------+
  192. | Type | Description |
  193. +===========================+==================================================+
  194. | boolean | Primitive boolean |
  195. +---------------------------+--------------------------------------------------+
  196. | integer | Primitive integer |
  197. +---------------------------+--------------------------------------------------+
  198. | double | Primitive double |
  199. +---------------------------+--------------------------------------------------+
  200. | string | Primitive string |
  201. +---------------------------+--------------------------------------------------+
  202. | array | An array with arbitrary keys, and values. |
  203. +---------------------------+--------------------------------------------------+
  204. | array<T> | A list of type T (T can be any available type). |
  205. | | Examples: |
  206. | | array<string>, array<MyNamespace\MyObject>, etc. |
  207. +---------------------------+--------------------------------------------------+
  208. | array<K, V> | A map of keys of type K to values of type V. |
  209. | | Examples: array<string, string>, |
  210. | | array<string, MyNamespace\MyObject>, etc. |
  211. +---------------------------+--------------------------------------------------+
  212. | DateTime | PHP's DateTime object |
  213. +---------------------------+--------------------------------------------------+
  214. | T | Where T is a fully qualified class name. |
  215. +---------------------------+--------------------------------------------------+
  216. | ArrayCollection<T> | Similar to array<T>, but will be deserialized |
  217. | | into Doctrine's ArrayCollection class. |
  218. +---------------------------+--------------------------------------------------+
  219. | ArrayCollection<K, V> | Similar to array<K, V>, but will be deserialized |
  220. | | into Doctrine's ArrayCollection class. |
  221. +---------------------------+--------------------------------------------------+
  222. Examples::
  223. <?php
  224. namespace MyNamespace;
  225. use JMS\SerializerBundle\Annotation\Type;
  226. class BlogPost
  227. {
  228. /**
  229. * @Type("ArrayCollection<MyNamespace\Comment>")
  230. */
  231. private $comments;
  232. /**
  233. * @Type("string")
  234. */
  235. private $title;
  236. /**
  237. * @Type("MyNamespace\Author")
  238. */
  239. private $author;
  240. /**
  241. * @Type("DateTime")
  242. */
  243. private $createdAt;
  244. /**
  245. * @Type("boolean")
  246. */
  247. private $published;
  248. /**
  249. * @Type("array<string, string>")
  250. */
  251. private $keyValueStore;
  252. }
  253. @XmlRoot
  254. ~~~~~~~~
  255. This allows you to specify the name of the top-level element.
  256. ::
  257. <?php
  258. use JMS\SerializerBundle\Annotation\XmlRoot;
  259. /** @XmlRoot("user") */
  260. class User
  261. {
  262. private $name = 'Johannes';
  263. }
  264. Resulting XML::
  265. <user>
  266. <name><![CDATA[Johannes]]></name>
  267. </user>
  268. @XmlAttribute
  269. ~~~~~~~~~~~~~
  270. This allows you to mark properties which should be set as attributes,
  271. and not as child elements.
  272. ::
  273. <?php
  274. use JMS\SerializerBundle\Annotation\XmlAttribute;
  275. class User
  276. {
  277. /** @XmlAttribute */
  278. private $id = 1;
  279. private $name = 'Johannes';
  280. }
  281. Resulting XML::
  282. <result id="1">
  283. <name><![CDATA[Johannes]]></name>
  284. </result>
  285. @XmlList
  286. ~~~~~~~~
  287. This allows you to define several properties of how arrays should be
  288. serialized. This is very similar to @XmlMap, and should be used if the
  289. keys of the array are not important.
  290. ::
  291. <?php
  292. use JMS\SerializerBundle\Annotation\XmlList;
  293. use JMS\SerializerBundle\Annotation\XmlRoot;
  294. /** @XmlRoot("post") */
  295. class Post
  296. {
  297. /**
  298. * @XmlList(inline = true, entry = "comment")
  299. */
  300. private $comments = array(
  301. new Comment('Foo'),
  302. new Comment('Bar'),
  303. );
  304. }
  305. class Comment
  306. {
  307. private $text;
  308. public function __construct($text)
  309. {
  310. $this->text = $text;
  311. }
  312. }
  313. Resulting XML::
  314. <post>
  315. <comment>
  316. <text><![CDATA[Foo]]></text>
  317. </comment>
  318. <comment>
  319. <text><![CDATA[Bar]]></text>
  320. </comment>
  321. </post>
  322. @XmlMap
  323. ~~~~~~~
  324. Similar to @XmlList, but the keys of the array are meaningful.
  325. XML Reference
  326. -------------
  327. ::
  328. <!-- MyBundle\Resources\config\serializer\ClassName.xml -->
  329. <?xml version="1.0" encoding="UTF-8">
  330. <serializer>
  331. <class name="Fully\Qualified\ClassName" exclusion-policy="ALL" xml-root-name="foo-bar" exclude="true">
  332. <property name="some-property"
  333. exclude="true"
  334. expose="true"
  335. type="string"
  336. serialized-name="foo"
  337. since-version="1.0"
  338. until-version="1.1"
  339. xml-attribute="true"
  340. >
  341. <!-- You can also specify the type as element which is necessary if
  342. your type contains "<" or ">" characters. -->
  343. <type><![CDATA[]]></type>
  344. <xml-list inline="true" entry-name="foobar" />
  345. <xml-map inline="true" key-attribute-name="foo" entry-name="bar" />
  346. </property>
  347. <callback-method name="foo" type="pre-serialize" />
  348. <callback-method name="bar" type="post-serialize" />
  349. <callback-method name="baz" type="post-deserialize" />
  350. </class>
  351. </serializer>
  352. YAML Reference
  353. --------------
  354. ::
  355. # MyBundle\Resources\config\serializer\ClassName.xml
  356. Fully\Qualified\ClassName:
  357. exclusion_policy: ALL
  358. xml_root_name: foobar
  359. exclude: true
  360. properties:
  361. some-property:
  362. exclude: true
  363. expose: true
  364. type: string
  365. serialized_name: foo
  366. since_version: 1.0
  367. until_version: 1.1
  368. xml_attribute: true
  369. xml_list:
  370. inline: true
  371. entry_name: foo
  372. xml_map:
  373. inline: true
  374. key_attribute_name: foo
  375. entry_name: bar
  376. callback_methods:
  377. pre_serialize: [foo, bar]
  378. post_serialize: [foo, bar]
  379. post_deserialize: [foo, bar]