annotations.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. Annotations
  2. -----------
  3. @ExclusionPolicy
  4. ~~~~~~~~~~~~~~~~
  5. This annotation can be defined on a class to indicate the exclusion strategy
  6. that should be used for the class.
  7. +----------+----------------------------------------------------------------+
  8. | Policy | Description |
  9. +==========+================================================================+
  10. | all | all properties are excluded by default; only properties marked |
  11. | | with @Expose will be serialized/unserialized |
  12. +----------+----------------------------------------------------------------+
  13. | none | no properties are excluded by default; all properties except |
  14. | | those marked with @Exclude will be serialized/unserialized |
  15. +----------+----------------------------------------------------------------+
  16. @Exclude
  17. ~~~~~~~~
  18. This annotation can be defined on a property to indicate that the property should
  19. not be serialized/unserialized. Works only in combination with NoneExclusionPolicy.
  20. If the ``ExpressionLanguageExclusionStrategy`` exclusion strategy is enabled, will
  21. be possible to use ``@Exclude(if="expression")`` to exclude dynamically a property.
  22. @Expose
  23. ~~~~~~~
  24. This annotation can be defined on a property to indicate that the property should
  25. be serialized/unserialized. Works only in combination with AllExclusionPolicy.
  26. If the ``ExpressionLanguageExclusionStrategy`` exclusion strategy is enabled, will
  27. be possible to use ``@Expose(if="expression")`` to expose dynamically a property.
  28. @SkipWhenEmpty
  29. ~~~~~~~~~~~~~~
  30. This annotation can be defined on a property to indicate that the property should
  31. not be serialized if the result will be "empty".
  32. Works option works only when serializing.
  33. @SerializedName
  34. ~~~~~~~~~~~~~~~
  35. This annotation can be defined on a property to define the serialized name for a
  36. property. If this is not defined, the property will be translated from camel-case
  37. to a lower-cased underscored name, e.g. camelCase -> camel_case.
  38. @Since
  39. ~~~~~~
  40. This annotation can be defined on a property to specify starting from which
  41. version this property is available. If an earlier version is serialized, then
  42. this property is excluded automatically. The version must be in a format that is
  43. understood by PHP's ``version_compare`` function.
  44. @Until
  45. ~~~~~~
  46. This annotation can be defined on a property to specify until which version this
  47. property was available. If a later version is serialized, then this property is
  48. excluded automatically. The version must be in a format that is understood by
  49. PHP's ``version_compare`` function.
  50. @Groups
  51. ~~~~~~~
  52. This annotation can be defined on a property to specify if the property
  53. should be serialized when only serializing specific groups (see
  54. :doc:`../cookbook/exclusion_strategies`).
  55. @MaxDepth
  56. ~~~~~~~~~
  57. This annotation can be defined on a property to limit the depth to which the
  58. content will be serialized. It is very useful when a property will contain a
  59. large object graph.
  60. @AccessType
  61. ~~~~~~~~~~~
  62. This annotation can be defined on a property, or a class to specify in which way
  63. the properties should be accessed. By default, the serializer will retrieve, or
  64. set the value via reflection, but you may change this to use a public method instead:
  65. .. code-block :: php
  66. <?php
  67. use JMS\Serializer\Annotation\AccessType;
  68. /** @AccessType("public_method") */
  69. class User
  70. {
  71. private $name;
  72. public function getName()
  73. {
  74. return $this->name;
  75. }
  76. public function setName($name)
  77. {
  78. $this->name = trim($name);
  79. }
  80. }
  81. @Accessor
  82. ~~~~~~~~~
  83. This annotation can be defined on a property to specify which public method should
  84. be called to retrieve, or set the value of the given property:
  85. .. code-block :: php
  86. <?php
  87. use JMS\Serializer\Annotation\Accessor;
  88. class User
  89. {
  90. private $id;
  91. /** @Accessor(getter="getTrimmedName",setter="setName") */
  92. private $name;
  93. // ...
  94. public function getTrimmedName()
  95. {
  96. return trim($this->name);
  97. }
  98. public function setName($name)
  99. {
  100. $this->name = $name;
  101. }
  102. }
  103. .. note ::
  104. If you need only to serialize your data, you can avoid providing a setter by
  105. setting the property as read-only using the ``@ReadOnly`` annotation.
  106. @AccessorOrder
  107. ~~~~~~~~~~~~~~
  108. This annotation can be defined on a class to control the order of properties. By
  109. default the order is undefined, but you may change it to either "alphabetical", or
  110. "custom".
  111. .. code-block :: php
  112. <?php
  113. use JMS\Serializer\Annotation\AccessorOrder;
  114. /**
  115. * @AccessorOrder("alphabetical")
  116. *
  117. * Resulting Property Order: id, name
  118. */
  119. class User
  120. {
  121. private $id;
  122. private $name;
  123. }
  124. /**
  125. * @AccessorOrder("custom", custom = {"name", "id"})
  126. *
  127. * Resulting Property Order: name, id
  128. */
  129. class User
  130. {
  131. private $id;
  132. private $name;
  133. }
  134. /**
  135. * @AccessorOrder("custom", custom = {"name", "someMethod" ,"id"})
  136. *
  137. * Resulting Property Order: name, mood, id
  138. */
  139. class User
  140. {
  141. private $id;
  142. private $name;
  143. /**
  144. * @Serializer\VirtualProperty
  145. * @Serializer\SerializedName("mood")
  146. *
  147. * @return string
  148. */
  149. public function getSomeMethod()
  150. {
  151. return 'happy';
  152. }
  153. }
  154. @VirtualProperty
  155. ~~~~~~~~~~~~~~~~
  156. This annotation can be defined on a method to indicate that the data returned by
  157. the method should appear like a property of the object.
  158. A virtual property can be defined for a method of an object to serialize and can be
  159. also defined at class level exposing data using the Symfony Expression Language.
  160. .. code-block :: php
  161. /**
  162. * @Serializer\VirtualProperty(
  163. * "firstName",
  164. * exp="object.getFirstName()",
  165. * options={@Serializer\SerializedName("my_first_name")}
  166. * )
  167. */
  168. class Author
  169. {
  170. /**
  171. * @Serializer\Expose()
  172. */
  173. private $id;
  174. /**
  175. * @Serializer\Exclude()
  176. */
  177. private $firstName;
  178. /**
  179. * @Serializer\Exclude()
  180. */
  181. private $lastName;
  182. /**
  183. * @Serializer\VirtualProperty()
  184. */
  185. public function getLastName()
  186. {
  187. return $this->lastName;
  188. }
  189. public function getFirstName()
  190. {
  191. return $this->firstName;
  192. }
  193. }
  194. In this example:
  195. - ``id`` is exposed using the object reflection.
  196. - ``lastName`` is exposed using the ``getLastName`` getter method.
  197. - ``firstName`` is exposed using the ``object.getFirstName()`` expression (``exp`` can contain any valid symfony expression).
  198. .. note ::
  199. This only works for serialization and is completely ignored during deserialization.
  200. @Inline
  201. ~~~~~~~
  202. This annotation can be defined on a property to indicate that the data of the property
  203. should be inlined.
  204. **Note**: This only works for serialization, the serializer will not be able to deserialize
  205. objects with this annotation. Also, AccessorOrder will be using the name of the property
  206. to determine the order.
  207. @ReadOnly
  208. ~~~~~~~~~
  209. This annotation can be defined on a property to indicate that the data of the property
  210. is read only and cannot be set during deserialization.
  211. A property can be marked as non read only with ``@ReadOnly(false)`` annotation (useful when a class is marked as read only).
  212. @PreSerialize
  213. ~~~~~~~~~~~~~
  214. This annotation can be defined on a method which is supposed to be called before
  215. the serialization of the object starts.
  216. @PostSerialize
  217. ~~~~~~~~~~~~~~
  218. This annotation can be defined on a method which is then called directly after the
  219. object has been serialized.
  220. @PostDeserialize
  221. ~~~~~~~~~~~~~~~~
  222. This annotation can be defined on a method which is supposed to be called after
  223. the object has been deserialized.
  224. @HandlerCallback
  225. ~~~~~~~~~~~~~~~~
  226. This annotation can be defined on a method if serialization/deserialization is handled
  227. by the object itself.
  228. .. code-block :: php
  229. <?php
  230. class Article
  231. {
  232. /**
  233. * @HandlerCallback("xml", direction = "serialization")
  234. */
  235. public function serializeToXml(XmlSerializationVisitor $visitor)
  236. {
  237. // custom logic here
  238. }
  239. }
  240. @Discriminator
  241. ~~~~~~~~~~~~~~
  242. .. versionadded : 0.12
  243. @Discriminator was added
  244. This annotation allows deserialization of relations which are polymorphic, but
  245. where a common base class exists. The ``@Discriminator`` annotation has to be applied
  246. to the least super type::
  247. /**
  248. * @Discriminator(field = "type", disabled = false, map = {"car": "Car", "moped": "Moped"}, groups={"foo", "bar"})
  249. */
  250. abstract class Vehicle { }
  251. class Car extends Vehicle { }
  252. class Moped extends Vehicle { }
  253. .. note ::
  254. `groups` is optional and is used as exclusion policy.
  255. @Type
  256. ~~~~~
  257. This annotation can be defined on a property to specify the type of that property.
  258. For deserialization, this annotation must be defined. For serialization, you may
  259. define it in order to enhance the produced output; for example, you may want to
  260. force a certain format to be used for DateTime types.
  261. Available Types:
  262. +-------------------------------------+--------------------------------------------------+
  263. | Type | Description |
  264. +=====================================+==================================================+
  265. | boolean | Primitive boolean |
  266. +-------------------------------------+--------------------------------------------------+
  267. | integer or int | Primitive integer |
  268. +-------------------------------------+--------------------------------------------------+
  269. | double or float | Primitive double |
  270. +-------------------------------------+--------------------------------------------------+
  271. | string | Primitive string |
  272. +-------------------------------------+--------------------------------------------------+
  273. | array | An array with arbitrary keys, and values. |
  274. +-------------------------------------+--------------------------------------------------+
  275. | array<T> | A list of type T (T can be any available type). |
  276. | | Examples: |
  277. | | array<string>, array<MyNamespace\MyObject>, etc. |
  278. +-------------------------------------+--------------------------------------------------+
  279. | array<K, V> | A map of keys of type K to values of type V. |
  280. | | Examples: array<string, string>, |
  281. | | array<string, MyNamespace\MyObject>, etc. |
  282. +-------------------------------------+--------------------------------------------------+
  283. | DateTime | PHP's DateTime object (default format/timezone) |
  284. +-------------------------------------+--------------------------------------------------+
  285. | DateTime<'format'> | PHP's DateTime object (custom format/default |
  286. | | timezone) |
  287. +-------------------------------------+--------------------------------------------------+
  288. | DateTime<'format', 'zone'> | PHP's DateTime object (custom format/timezone) |
  289. +-------------------------------------+--------------------------------------------------+
  290. | DateTimeImmutable | PHP's DateTimeImmutable object (default format/ |
  291. | | timezone) |
  292. +-------------------------------------+--------------------------------------------------+
  293. | DateTimeImmutable<'format'> | PHP's DateTimeImmutable object (custom format/ |
  294. | | default timezone) |
  295. +-------------------------------------+--------------------------------------------------+
  296. | DateTimeImmutable<'format', 'zone'> | PHP's DateTimeImmutable object (custom format/ |
  297. | | timezone) |
  298. +-------------------------------------+--------------------------------------------------+
  299. | DateInterval | PHP's DateInterval object using ISO 8601 format |
  300. +-------------------------------------+--------------------------------------------------+
  301. | T | Where T is a fully qualified class name. |
  302. +-------------------------------------+--------------------------------------------------+
  303. | ArrayCollection<T> | Similar to array<T>, but will be deserialized |
  304. | | into Doctrine's ArrayCollection class. |
  305. +-------------------------------------+--------------------------------------------------+
  306. | ArrayCollection<K, V> | Similar to array<K, V>, but will be deserialized |
  307. | | into Doctrine's ArrayCollection class. |
  308. +-------------------------------------+--------------------------------------------------+
  309. Examples:
  310. .. code-block :: php
  311. <?php
  312. namespace MyNamespace;
  313. use JMS\Serializer\Annotation\Type;
  314. class BlogPost
  315. {
  316. /**
  317. * @Type("ArrayCollection<MyNamespace\Comment>")
  318. */
  319. private $comments;
  320. /**
  321. * @Type("string")
  322. */
  323. private $title;
  324. /**
  325. * @Type("MyNamespace\Author")
  326. */
  327. private $author;
  328. /**
  329. * @Type("DateTime")
  330. */
  331. private $startAt;
  332. /**
  333. * @Type("DateTime<'Y-m-d'>")
  334. */
  335. private $endAt;
  336. /**
  337. * @Type("DateTimeImmutable")
  338. */
  339. private $createdAt;
  340. /**
  341. * @Type("DateTimeImmutable<'Y-m-d'>")
  342. */
  343. private $updatedAt;
  344. /**
  345. * @Type("boolean")
  346. */
  347. private $published;
  348. /**
  349. * @Type("array<string, string>")
  350. */
  351. private $keyValueStore;
  352. }
  353. @XmlRoot
  354. ~~~~~~~~
  355. This allows you to specify the name of the top-level element.
  356. .. code-block :: php
  357. <?php
  358. use JMS\Serializer\Annotation\XmlRoot;
  359. /** @XmlRoot("user") */
  360. class User
  361. {
  362. private $name = 'Johannes';
  363. }
  364. Resulting XML:
  365. .. code-block :: xml
  366. <user>
  367. <name><![CDATA[Johannes]]></name>
  368. </user>
  369. .. note ::
  370. @XmlRoot only applies to the root element, but is for example not taken into
  371. account for collections. You can define the entry name for collections using
  372. @XmlList, or @XmlMap.
  373. @XmlAttribute
  374. ~~~~~~~~~~~~~
  375. This allows you to mark properties which should be set as attributes,
  376. and not as child elements.
  377. .. code-block :: php
  378. <?php
  379. use JMS\Serializer\Annotation\XmlAttribute;
  380. class User
  381. {
  382. /** @XmlAttribute */
  383. private $id = 1;
  384. private $name = 'Johannes';
  385. }
  386. Resulting XML:
  387. .. code-block :: xml
  388. <result id="1">
  389. <name><![CDATA[Johannes]]></name>
  390. </result>
  391. @XmlDiscriminator
  392. ~~~~~~~~~~~~~~~~~
  393. This annotation allows to modify the behaviour of @Discriminator regarding handling of XML.
  394. Available Options:
  395. +-------------------------------------+--------------------------------------------------+
  396. | Type | Description |
  397. +=====================================+==================================================+
  398. | attribute | use an attribute instead of a child node |
  399. +-------------------------------------+--------------------------------------------------+
  400. | cdata | render child node content with or without cdata |
  401. +-------------------------------------+--------------------------------------------------+
  402. | namespace | render child node using the specified namespace |
  403. +-------------------------------------+--------------------------------------------------+
  404. Example for "attribute":
  405. .. code-block :: php
  406. <?php
  407. use JMS\Serializer\Annotation\Discriminator;
  408. use JMS\Serializer\Annotation\XmlDiscriminator;
  409. /**
  410. * @Discriminator(field = "type", map = {"car": "Car", "moped": "Moped"}, groups={"foo", "bar"})
  411. * @XmlDiscriminator(attribute=true)
  412. */
  413. abstract class Vehicle { }
  414. class Car extends Vehicle { }
  415. Resulting XML:
  416. .. code-block :: xml
  417. <vehicle type="car" />
  418. Example for "cdata":
  419. .. code-block :: php
  420. <?php
  421. use JMS\Serializer\Annotation\Discriminator;
  422. use JMS\Serializer\Annotation\XmlDiscriminator;
  423. /**
  424. * @Discriminator(field = "type", map = {"car": "Car", "moped": "Moped"}, groups={"foo", "bar"})
  425. * @XmlDiscriminator(attribute=true)
  426. */
  427. abstract class Vehicle { }
  428. class Car extends Vehicle { }
  429. Resulting XML:
  430. .. code-block :: xml
  431. <vehicle><type>car</type></vehicle>
  432. @XmlValue
  433. ~~~~~~~~~
  434. This allows you to mark properties which should be set as the value of the
  435. current element. Note that this has the limitation that any additional
  436. properties of that object must have the @XmlAttribute annotation.
  437. XMlValue also has property cdata. Which has the same meaning as the one in
  438. XMLElement.
  439. .. code-block :: php
  440. <?php
  441. use JMS\Serializer\Annotation\XmlAttribute;
  442. use JMS\Serializer\Annotation\XmlValue;
  443. use JMS\Serializer\Annotation\XmlRoot;
  444. /** @XmlRoot("price") */
  445. class Price
  446. {
  447. /** @XmlAttribute */
  448. private $currency = 'EUR';
  449. /** @XmlValue */
  450. private $amount = 1.23;
  451. }
  452. Resulting XML:
  453. .. code-block :: xml
  454. <price currency="EUR">1.23</price>
  455. @XmlList
  456. ~~~~~~~~
  457. This allows you to define several properties of how arrays should be
  458. serialized. This is very similar to @XmlMap, and should be used if the
  459. keys of the array are not important.
  460. .. code-block :: php
  461. <?php
  462. use JMS\Serializer\Annotation\XmlList;
  463. use JMS\Serializer\Annotation\XmlRoot;
  464. /** @XmlRoot("post") */
  465. class Post
  466. {
  467. /**
  468. * @XmlList(inline = true, entry = "comment")
  469. */
  470. private $comments = array(
  471. new Comment('Foo'),
  472. new Comment('Bar'),
  473. );
  474. }
  475. class Comment
  476. {
  477. private $text;
  478. public function __construct($text)
  479. {
  480. $this->text = $text;
  481. }
  482. }
  483. Resulting XML:
  484. .. code-block :: xml
  485. <post>
  486. <comment>
  487. <text><![CDATA[Foo]]></text>
  488. </comment>
  489. <comment>
  490. <text><![CDATA[Bar]]></text>
  491. </comment>
  492. </post>
  493. You can also specify the entry tag namespace using the ``namespace`` attribute (``@XmlList(inline = true, entry = "comment", namespace="http://www.example.com/ns")``).
  494. @XmlMap
  495. ~~~~~~~
  496. Similar to @XmlList, but the keys of the array are meaningful.
  497. @XmlKeyValuePairs
  498. ~~~~~~~~~~~~~~~~~
  499. This allows you to use the keys of an array as xml tags.
  500. .. note ::
  501. When a key is an invalid xml tag name (e.g. 1_foo) the tag name *entry* will be used instead of the key.
  502. @XmlAttributeMap
  503. ~~~~~~~~~~~~~~~~
  504. This is similar to the @XmlKeyValuePairs, but instead of creating child elements, it creates attributes.
  505. .. code-block :: php
  506. <?php
  507. use JMS\Serializer\Annotation\XmlAttribute;
  508. class Input
  509. {
  510. /** @XmlAttributeMap */
  511. private $id = array(
  512. 'name' => 'firstname',
  513. 'value' => 'Adrien',
  514. );
  515. }
  516. Resulting XML:
  517. .. code-block :: xml
  518. <result name="firstname" value="Adrien"/>
  519. @XmlElement
  520. ~~~~~~~~~~~
  521. This annotation can be defined on a property to add additional xml serialization/deserialization properties.
  522. .. code-block :: php
  523. <?php
  524. use JMS\Serializer\Annotation\XmlElement;
  525. /**
  526. * @XmlNamespace(uri="http://www.w3.org/2005/Atom", prefix="atom")
  527. */
  528. class User
  529. {
  530. /**
  531. * @XmlElement(cdata=false, namespace="http://www.w3.org/2005/Atom")
  532. */
  533. private $id = 'my_id';
  534. }
  535. Resulting XML:
  536. .. code-block :: xml
  537. <atom:id>my_id</atom:id>
  538. @XmlNamespace
  539. ~~~~~~~~~~~~~
  540. This annotation allows you to specify Xml namespace/s and prefix used.
  541. .. code-block :: php
  542. <?php
  543. use JMS\Serializer\Annotation\XmlNamespace;
  544. /**
  545. * @XmlNamespace(uri="http://example.com/namespace")
  546. * @XmlNamespace(uri="http://www.w3.org/2005/Atom", prefix="atom")
  547. */
  548. class BlogPost
  549. {
  550. /**
  551. * @Type("JMS\Serializer\Tests\Fixtures\Author")
  552. * @Groups({"post"})
  553. * @XmlElement(namespace="http://www.w3.org/2005/Atom")
  554. */
  555. private $author;
  556. }
  557. class Author
  558. {
  559. /**
  560. * @Type("string")
  561. * @SerializedName("full_name")
  562. */
  563. private $name;
  564. }
  565. Resulting XML:
  566. .. code-block :: xml
  567. <?xml version="1.0" encoding="UTF-8"?>
  568. <blog-post xmlns="http://example.com/namespace" xmlns:atom="http://www.w3.org/2005/Atom">
  569. <atom:author>
  570. <full_name><![CDATA[Foo Bar]]></full_name>
  571. </atom:author>
  572. </blog>