We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 36692
    • 13 Posts
    Let's say we have a table called item. And every time the user edits an item, we call
    $obj->save()

    I'd like to also do an INSERT into a table with all the same columns, called item_version, which would have a column called item_id. This would allow the easy querying of the item's change history. This is essentially like having a blog post that supports versioning, such that you can view history and rollback to previous versions by setting the version field on the main record.
    Seems like a common pattern, wondering how best to do this.
    Would you do something like
    $version_obj = $modx->newObject('ItemVersion', $obj->toArray());
    $version_obj->save();
    

    At every place in the code that saves, or is there some other best practice for accomplishing this automagically when a save occurs?
      • 33968
      • 863 Posts
      You can override the save() function in your object class file (/model/package/myobject.class.php). That way it will be executed whenever you call $obj->save().

      Not tested, but to give you some idea:
      <?php
      class myObject extends xPDOSimpleObject {
      
          // override the default save behaviour
          public function save() {
              $version_obj = $this->modx->newObject('ItemVersion', $this->toArray());
              $version_obj->save();
      
              // as we have overridden save(), trigger save() in xPDOSimpleObject
              parent :: save();
          }
      }