index.rst 15 KB

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