updating DataObjects

32 views
Skip to first unread message

Nicolaas Thiemen Francken

unread,
Jan 17, 2018, 12:19:39 AM1/17/18
to silverstripe-dev
Hi,

I was wondering what the best strategy is for updating all references to an Object.

Example (sequence of code)

(a) class 1: retrieves $order

(b) class 2: retrieves same $order (same ID) and changes value of $order->MyRelationshipID, followed by  $order->write();

.... and maybe ....
(b2) class 3: retrieves same $order (same ID) and changes value of $order->MyRelationshipID, followed by $order->write();
....

(c) class 1: checks  $order->MyRelationshipID value 

which is now out of date.

What do you recommend in terms of avoiding this situation where you can not always control that both class 1 and class 2 use the exact same object reference  (e.g. by the use of DataObject::get_one or a similar type of caching technique). 

I dont fully understand why or how this works yet.... but what seems to solve is to re-retrieve object from database:

$oder->MyRelationshipID is "OUTDATED"

$order = Order::get()->filter(['ID' => $order->ID])->first();

$oder->MyRelationshipID is "CORRECT"


It may perhaps relate to this issue: 
T
​hank you

Nicolaas​

Marcus Dalgren

unread,
Jan 17, 2018, 9:25:13 AM1/17/18
to SilverStripe Core Development
This is pretty much how most ORM:s work.
Each time you retrieve a data object from the database the object you get back is an instance of the table row (or whatever) AT THAT TIME.
If you retrieve it again then that's a new instance and they won't stay in sync if you start making changes to one of them.

My recommendation is to restructure your code so that the order in question gets delivered in to the class that's going to do the work.
The scenario you describe seems like a really bad structure programming wise to me.

If you for some reason have three different classes that need to do some work with an order then it's up to you to make sure they all work on the same one.
With the structure in your example you're fetching the order from the database at least three times which is really unnecessary.

Nicolaas Thiemen Francken

unread,
Jan 19, 2018, 1:02:50 AM1/19/18
to silverstripe-dev
Thank you for your detailed reply Marcus.

Totally agree that code could be designed better, but with lots of independent modules and extensions this is not always easy or foreseeable. 


​Nicolaas​

Reply all
Reply to author
Forward
0 new messages