index.rst 17 KB

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