Search code examples
phpormpropel

Propel "ModelCriteria::FORMAT_ON_DEMAND" reuses same object?


Apparently using ModelCriteria::FORMAT_ON_DEMAND (PropelOnDemandFormatter) does not only make Propel hydrate objects row by row and without instance pooling as documented, but hydration takes place on the very same object.

This means that $object in the example below will always stay the same, and only its contents will change.

$objects = ObjectQuery::create()
    ->setFormatter(ModelCriteria::FORMAT_ON_DEMAND)
    ->find();

foreach ($objects as $object) {
}

This becomes a problem if your Propel object has additional data that are not mapped to database table columns but managed in the object.

Why was this design chosen over, say, cleanly instantiating an object and then hydrating it? And what is the recommended way of working with this design decision?


Solution

  • My guess is that this is for better performance because no instantiation is necessary.

    If your code is expected to use on-demand fetching, you should probably override postHydrate() for the class of the object being fetched to perform any necessary object-related updates to data that Propel does not automatically map to columns.

    Note that ensureConsistency() is only called on "rehydration" which is apparently not the case here.

    Also, do not store object references. They will all refer to the same object with the record fetched last.