basic.simple-embedded-document.txt 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. Title: Simple Embeded Document Model
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. To fully understand this example please refer to [Embedded Documents Models Section][basic.embedded-documents]
  5. To use embedded documents you need to do two steps:
  6. - First create model for embedded document
  7. (we will add address as embedded document to User model from previous [example][basic.simple-model] ):
  8. ~~~
  9. [php]
  10. /**
  11. * Note that we extending EMongoEmbeddedDocument, not regular EMongoDocument class
  12. * this is for performance reasons, embedded documents do not need to have, all
  13. * connection, and collection management stuff, this is explained in [Embedded Documents Models Section][basic.embeddedDocuments]
  14. *
  15. * NOTE: You may define regular EMongoDocument as an embedded in another one, if you really want to, it will still work
  16. */
  17. class UserAddress extends EMongoEmbeddedDocument
  18. {
  19. public $apartment;
  20. public $house;
  21. public $street;
  22. public $city;
  23. public $zip;
  24. // We may define rules for embedded document too
  25. public function rules()
  26. {
  27. return array(
  28. array('apartment, house, street, city, zip', 'required'),
  29. // ...
  30. );
  31. }
  32. // And attribute names too
  33. public function attributeNames() { /* ... */ }
  34. // NOTE: for embedded documents we do not define static model method!
  35. // we do not define getCollectionName method either.
  36. }
  37. ~~~
  38. - Next we have to define `embeddedDocuments()` method in model that will contain embedded document
  39. Add `embeddedDocument()` method to previous `User` model example:
  40. ~~~
  41. [php]
  42. class User extends EMongoDocument
  43. {
  44. // ...
  45. /**
  46. * This method should return simple array that will define field names for embedded
  47. * documents, and class to use for them
  48. */
  49. public function embeddedDocuments()
  50. {
  51. return array(
  52. // property field name => class name to use for this embedded document
  53. 'address' => 'UserAddress',
  54. );
  55. }
  56. // ...
  57. }
  58. ~~~
  59. Now, the fun part starts!
  60. We can now do things like:
  61. ~~~
  62. [php]
  63. $user = new User();
  64. $user->address->city = 'New York';
  65. $user->address->street = 'Some street name';
  66. // This will save user to users collection, with UserAddress embedded document set,
  67. // and this handle with validation of embedded documents too!
  68. $user->save();
  69. // After that:
  70. $user = User::model()->find();
  71. // Models will be automatically populated with embedded documents that they contain,
  72. // so we can do:
  73. echo $user->address->city;
  74. ~~~