index.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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($this),
  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. Note the order in which the handlers are listed in the "handlers" section defines
  81. in which they are called while processing. See "extending.rst" for details for how
  82. to define custom handlers, which then also need to be configured as shown here.
  83. Usage
  84. -----
  85. De-/Serializing Objects
  86. ~~~~~~~~~~~~~~~~~~~~~~~
  87. ::
  88. $serializer = $container->get('serializer');
  89. $serializer->serialize(new MyObject(), 'json');
  90. $serializer->serialize(new MyObject(), 'xml');
  91. The serializer supports JSON, and XML out-of-the-box, and can also handle
  92. many custom XML features (see below).
  93. The serializer can also be accessed via a Twig filter and will default to
  94. "json".
  95. ::
  96. {{ myObject | serialize | raw }}
  97. {{ myObject | serialize('xml') | raw }}
  98. Versioning
  99. ~~~~~~~~~~
  100. The bundle allows you to have different versions of your objects. This can be
  101. achieved by using the @Since, and @Until annotation which both accept a
  102. standardized PHP version number.
  103. ::
  104. <?php
  105. class VersionedObject
  106. {
  107. /**
  108. * @Until("1.0.x")
  109. */
  110. private $name;
  111. /**
  112. * @Since("1.1")
  113. * @SerializedName("name")
  114. */
  115. private $name2;
  116. }
  117. If you have annotated your objects like above, you can serializing different
  118. versions like this::
  119. <?php
  120. $serializer->setVersion('1.0');
  121. $serializer->serialize(new VersionObject(), 'json');
  122. Defining which properties should be serialized
  123. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  124. The default exclusion policy is to exclude nothing, that is all properties of the
  125. object will be serialized. If you only want to expose a few of the properties,
  126. then it is easier to change the exclusion policy, and only mark these few properties::
  127. <?php
  128. use JMS\SerializerBundle\Annotation\ExclusionPolicy;
  129. use JMS\SerializerBundle\Annotation\Expose;
  130. /**
  131. * The following annotations tells the serializer to skip all properties which
  132. * have not marked with @Expose.
  133. *
  134. * @ExclusionPolicy("all")
  135. */
  136. class MyObject
  137. {
  138. private $foo;
  139. private $bar;
  140. /**
  141. * @Expose
  142. */
  143. private $name;
  144. }
  145. Lifecycle Callbacks
  146. ~~~~~~~~~~~~~~~~~~~
  147. If you need to run some custom logic during the serialization process, you can use
  148. one of these lifecycle callbacks: @PreSerialize, @PostSerialize, or @PostDeserialize
  149. Annotations
  150. -----------
  151. @ExclusionPolicy
  152. ~~~~~~~~~~~~~~~~
  153. This annotation can be defined on a class to indicate the exclusion strategy
  154. that should be used for the class.
  155. +----------+----------------------------------------------------------------+
  156. | Policy | Description |
  157. +==========+================================================================+
  158. | all | all properties are excluded by default; only properties marked |
  159. | | with @Expose will be serialized/unserialized |
  160. +----------+----------------------------------------------------------------+
  161. | none | no properties are excluded by default; all properties except |
  162. | | those marked with @Exclude will be serialized/unserialized |
  163. +----------+----------------------------------------------------------------+
  164. @Exclude
  165. ~~~~~~~~
  166. This annotation can be defined on a property to indicate that the property should
  167. not be serialized/unserialized. Works only in combination with NoneExclusionPolicy.
  168. @Expose
  169. ~~~~~~~
  170. This annotation can be defined on a property to indicate that the property should
  171. be serialized/unserialized. Works only in combination with AllExclusionPolicy.
  172. @SerializedName
  173. ~~~~~~~~~~~~~~~
  174. This annotation can be defined on a property to define the serialized name for a
  175. property. If this is not defined, the property will be translated from camel-case
  176. to a lower-cased underscored name, e.g. camelCase -> camel_case.
  177. @Since
  178. ~~~~~~
  179. This annotation can be defined on a property to specify starting from which
  180. version this property is available. If an earlier version is serialized, then
  181. this property is excluded automatically. The version must be in a format that is
  182. understood by PHP's ``version_compare`` function.
  183. @Until
  184. ~~~~~~
  185. This annotation can be defined on a property to specify until which version this
  186. property was available. If a later version is serialized, then this property is
  187. excluded automatically. The version must be in a format that is understood by
  188. PHP's ``version_compare`` function.
  189. @PreSerialize
  190. ~~~~~~~~~~~~~
  191. This annotation can be defined on a method which is supposed to be called before
  192. the serialization of the object starts.
  193. @PostSerialize
  194. ~~~~~~~~~~~~~~
  195. This annotation can be defined on a method which is then called directly after the
  196. object has been serialized.
  197. @PostDeserialize
  198. ~~~~~~~~~~~~~~~~
  199. This annotation can be defined on a method which is supposed to be called after
  200. the object has been deserialized.
  201. @Type
  202. ~~~~~
  203. This annotation can be defined on a property to specify the type of that property.
  204. This annotation must only be defined when you want to be able to deserialize an
  205. object.
  206. Available Types:
  207. +---------------------------+--------------------------------------------------+
  208. | Type | Description |
  209. +===========================+==================================================+
  210. | boolean | Primitive boolean |
  211. +---------------------------+--------------------------------------------------+
  212. | integer | Primitive integer |
  213. +---------------------------+--------------------------------------------------+
  214. | double | Primitive double |
  215. +---------------------------+--------------------------------------------------+
  216. | string | Primitive string |
  217. +---------------------------+--------------------------------------------------+
  218. | array | An array with arbitrary keys, and values. |
  219. +---------------------------+--------------------------------------------------+
  220. | array<T> | A list of type T (T can be any available type). |
  221. | | Examples: |
  222. | | array<string>, array<MyNamespace\MyObject>, etc. |
  223. +---------------------------+--------------------------------------------------+
  224. | array<K, V> | A map of keys of type K to values of type V. |
  225. | | Examples: array<string, string>, |
  226. | | array<string, MyNamespace\MyObject>, etc. |
  227. +---------------------------+--------------------------------------------------+
  228. | DateTime | PHP's DateTime object |
  229. +---------------------------+--------------------------------------------------+
  230. | T | Where T is a fully qualified class name. |
  231. +---------------------------+--------------------------------------------------+
  232. | ArrayCollection<T> | Similar to array<T>, but will be deserialized |
  233. | | into Doctrine's ArrayCollection class. |
  234. +---------------------------+--------------------------------------------------+
  235. | ArrayCollection<K, V> | Similar to array<K, V>, but will be deserialized |
  236. | | into Doctrine's ArrayCollection class. |
  237. +---------------------------+--------------------------------------------------+
  238. Examples::
  239. <?php
  240. namespace MyNamespace;
  241. use JMS\SerializerBundle\Annotation\Type;
  242. class BlogPost
  243. {
  244. /**
  245. * @Type("ArrayCollection<MyNamespace\Comment>")
  246. */
  247. private $comments;
  248. /**
  249. * @Type("string")
  250. */
  251. private $title;
  252. /**
  253. * @Type("MyNamespace\Author")
  254. */
  255. private $author;
  256. /**
  257. * @Type("DateTime")
  258. */
  259. private $createdAt;
  260. /**
  261. * @Type("boolean")
  262. */
  263. private $published;
  264. /**
  265. * @Type("array<string, string>")
  266. */
  267. private $keyValueStore;
  268. }
  269. @XmlRoot
  270. ~~~~~~~~
  271. This allows you to specify the name of the top-level element.
  272. ::
  273. <?php
  274. use JMS\SerializerBundle\Annotation\XmlRoot;
  275. /** @XmlRoot("user") */
  276. class User
  277. {
  278. private $name = 'Johannes';
  279. }
  280. Resulting XML::
  281. <user>
  282. <name><![CDATA[Johannes]]></name>
  283. </user>
  284. @XmlAttribute
  285. ~~~~~~~~~~~~~
  286. This allows you to mark properties which should be set as attributes,
  287. and not as child elements.
  288. ::
  289. <?php
  290. use JMS\SerializerBundle\Annotation\XmlAttribute;
  291. class User
  292. {
  293. /** @XmlAttribute */
  294. private $id = 1;
  295. private $name = 'Johannes';
  296. }
  297. Resulting XML::
  298. <result id="1">
  299. <name><![CDATA[Johannes]]></name>
  300. </result>
  301. @XmlValue
  302. ~~~~~~~~~
  303. This allows you to mark properties which should be set as the value of the
  304. current element. Note that this has the limitation that any additional
  305. properties of that object must have the @XmlAttribute annotation.
  306. ::
  307. <?php
  308. use JMS\SerializerBundle\Annotation\XmlAttribute;
  309. use JMS\SerializerBundle\Annotation\XmlValue;
  310. use JMS\SerializerBundle\Annotation\XmlRoot;
  311. /** @XmlRoot("price") */
  312. class Price
  313. {
  314. /** @XmlAttribute */
  315. private $currency = 'EUR';
  316. /** @XmlValue */
  317. private $amount = 1.23;
  318. }
  319. Resulting XML::
  320. <price currency="EUR">1.23</price>
  321. @XmlList
  322. ~~~~~~~~
  323. This allows you to define several properties of how arrays should be
  324. serialized. This is very similar to @XmlMap, and should be used if the
  325. keys of the array are not important.
  326. ::
  327. <?php
  328. use JMS\SerializerBundle\Annotation\XmlList;
  329. use JMS\SerializerBundle\Annotation\XmlRoot;
  330. /** @XmlRoot("post") */
  331. class Post
  332. {
  333. /**
  334. * @XmlList(inline = true, entry = "comment")
  335. */
  336. private $comments = array(
  337. new Comment('Foo'),
  338. new Comment('Bar'),
  339. );
  340. }
  341. class Comment
  342. {
  343. private $text;
  344. public function __construct($text)
  345. {
  346. $this->text = $text;
  347. }
  348. }
  349. Resulting XML::
  350. <post>
  351. <comment>
  352. <text><![CDATA[Foo]]></text>
  353. </comment>
  354. <comment>
  355. <text><![CDATA[Bar]]></text>
  356. </comment>
  357. </post>
  358. @XmlMap
  359. ~~~~~~~
  360. Similar to @XmlList, but the keys of the array are meaningful.
  361. XML Reference
  362. -------------
  363. ::
  364. <!-- MyBundle\Resources\config\serializer\ClassName.xml -->
  365. <?xml version="1.0" encoding="UTF-8">
  366. <serializer>
  367. <class name="Fully\Qualified\ClassName" exclusion-policy="ALL" xml-root-name="foo-bar" exclude="true">
  368. <property name="some-property"
  369. exclude="true"
  370. expose="true"
  371. type="string"
  372. serialized-name="foo"
  373. since-version="1.0"
  374. until-version="1.1"
  375. xml-attribute="true"
  376. >
  377. <!-- You can also specify the type as element which is necessary if
  378. your type contains "<" or ">" characters. -->
  379. <type><![CDATA[]]></type>
  380. <xml-list inline="true" entry-name="foobar" />
  381. <xml-map inline="true" key-attribute-name="foo" entry-name="bar" />
  382. </property>
  383. <callback-method name="foo" type="pre-serialize" />
  384. <callback-method name="bar" type="post-serialize" />
  385. <callback-method name="baz" type="post-deserialize" />
  386. </class>
  387. </serializer>
  388. YAML Reference
  389. --------------
  390. ::
  391. # MyBundle\Resources\config\serializer\ClassName.yml
  392. Fully\Qualified\ClassName:
  393. exclusion_policy: ALL
  394. xml_root_name: foobar
  395. exclude: true
  396. properties:
  397. some-property:
  398. exclude: true
  399. expose: true
  400. type: string
  401. serialized_name: foo
  402. since_version: 1.0
  403. until_version: 1.1
  404. xml_attribute: true
  405. xml_list:
  406. inline: true
  407. entry_name: foo
  408. xml_map:
  409. inline: true
  410. key_attribute_name: foo
  411. entry_name: bar
  412. callback_methods:
  413. pre_serialize: [foo, bar]
  414. post_serialize: [foo, bar]
  415. post_deserialize: [foo, bar]