View more context

 

jakx

Does anyone here have a strong preference for which pattern to use when creating a DataObject?

e.g

  1. $obj = MyDataObject::create([
  2. 'Field' => 'Value',
  3. ]);

vs

  1. $obj = MyDataObject::create();
  2. $obj->Field = 'Value';

vs something else?

jakx

I notice if the later is well annotated, code-intel gives those properties quicker references, and make them traversable, but there's repeated use of the $obj variable

nightjarnz

@jakx there is a critical difference in those two methods :)

😮 (2)
Firesphere

Added to my favourites 😄

😃 (1) 😄 (1)
nightjarnz

the first is setting the initial state - e.g. when the object is created from the DB. If you then perform a write, nothing will happen (unless there is no ID). The second explicitly updates an existing (in memory) DataObject, which flicks the changed status. Writes will see there are changes to record, and so continues happily.

nightjarnz

the better equivalent for what you're trying to achieve with the first call is MyDataObject::create()->update(['Field' => 'Value'])

nightjarnz

of course, this is a little nitpicky, because if you're creating a brand new object, then there's no ID which means isInDatabase is false, meaning a write happens and folks are generally none the wiser.

nightjarnz

But this is certainly a gotcha I've run into before (a long time ago, but it's a lasting memory, which still holds true).

👍 (1)
nightjarnz

In terms of strong preference over update(...) or ->Field = ..., no I don't think there is one.

🤔 (1)
nightjarnz

I tend to prefer the former for brevity in calls. But it depends on how much you're trying to update at once really.