Stop Caching Relations Inside Your Models in PHP
Database models are the heart of your application. Restrain yourself from caching anything inside!
I intend this story to be less wordy, but fruitful and valuable nonetheless, I hope. It’s about caching and repeated patterns of caching relations inside database models in general.
I have seen this lately a lot with Eloquent Models in Laravel, but the issue applies to other Object Relational Mappers too.
Keep in mind that Domain Objects belong to the domain layer of an application while caching is an infrastructural detail inside (a totally) different layer: domain and infrastructural layers must not mix.
Remember that temporary, in-memory arrays inside models is also caching. It simply uses different cache storage:
private static array $cache;
public function getSomeCachedRelation()
{
if (false === isset(self::$cache)) {
self::$cache = // populate cache
}
return self::$cache;
}
Domain models are on the writing part of the application. Using domain models should not be used in the read context.
Most programmers use the same object for write operations and then pass the same object to the view.