What do you do if you need to iterate over a lot of loaded entities during a single
request or background process, like a Drush command? I thought it would be as easy as
… until I found out that the ContentEntityStorageBase class (which accounts for most
entities you would ever need this for) resets both the persistent cache and static cache
in it’s resetCache method (despite the point of that method being for static cache clearing).
This leaves us in a sticky situation, as you don’t want to flush the persistent cache for
all of your entities just to iterate over them.
This is a modified version of the core patch I submitted above:
Did you see what is happening?
In order to just clear the static cache for entity storage, we can reset the $entities
property. However, this is a protected property! Closure::bindTo() the rescue.
Using Closure::bindTo() we can create a closure that resets $this->entities - we can then bind this to the entity
storage class itself to clear the entities property in the context of that class. Pretty cool. Somewhat a hack, but needs
must ‘n’ all that.