advanced.soft-models.txt 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. Title: Soft Documents Models
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. Since the 1.3.4 version you can have models, that do not have fixed attribute list.
  5. The only thing to get started is to define model that extends from `EMongoSoftDocument`
  6. Example:
  7. ~~~
  8. [php]
  9. class MixedModel extends EMongoSoftDocument
  10. {
  11. // You still can define a field(s), that always will be defined
  12. // like in normal EMongoDocument, but this is optional
  13. public $field;
  14. // As always define the getCollectionName() and model() methods !
  15. public function getCollectionName()
  16. {
  17. return 'mixed_collection';
  18. }
  19. public static function model($className=__CLASS__)
  20. {
  21. return parent::model($className);
  22. }
  23. }
  24. ~~~
  25. And thats it! Now you have model class that will handle of any field lists!
  26. > [information]
  27. > You still can use all features that are present in `EMongoDocument` because 'EMongoSoftDocument` extends from it.
  28. ## Usage: {#usage}
  29. > [important]
  30. > You need to init every soft attribute that you want to add to model, by using `$model->initSoftAttribute($attributeName)`.
  31. ~~~
  32. [php]
  33. $model = new MixedModel();
  34. $model->initSoftAttribute('field1');
  35. $model->initSoftAttributes(array('field2', 'field3'));
  36. $model->field = 'regularField';
  37. $model->field1 = 'value'; // }
  38. $model->field2 = 'value2'; // } soft attributes, only in this model instance
  39. $model->field3 = 'value3'; // }
  40. $model->save();
  41. // Finder will init and populate all soft attributes with values found in particular document automatically
  42. $newModel = MixedModel::model()->find();
  43. echo $newModel->field3; // will print 'value3'
  44. ~~~