[Quick+CacheBox] Are Quick Entities Safe for Caching?

I’m looking for guidance on CacheBox + Quick best practices.

Is caching a live Quick entity across requests considered supported/safe, or is the recommended pattern to cache raw attribute data and rehydrate a fresh entity on cache hit?

If live entity caching is not recommended, what is the preferred pattern?
For example, I could cache raw persistent attributes and call hydrate() like this:

private function getPost( required numeric postId ) {
        
	var cacheKey = "post-#postId#";

	if ( cache.lookup( cacheKey ) ) {
		return hydratePost( cache.get( cacheKey ) );
	}

	var post = fetchPost( postId );

	// Cache raw attributes, not the live Quick entity instance.
	cache.set( cacheKey, post.retrieveAttributesData() );

	return post;

}

private Post function fetchPost( required numeric postId ) {
	return wirebox.getInstance( "Post" ).findOrFail( arguments.postId );
}

private Post function hydratePost( required struct attributes ) {
	return wirebox.getInstance( "Post" )
		.hydrate( arguments.attributes )
}

Also, if caching live entities is unsafe, would it make sense to document that explicitly in the Quick docs? If so, I am happy to offer a draft, but I would need guidance on which section of the docs it belongs in.

I try to only cache serializable data, so I’d avoid serializing the entire Quick entity. I’d instead cache the attributes or memento.

The hydrate vs fetch is more a question of how up-to-date does your application need to be? If stale data is an acceptable trade-off for the caching speed, then hydrating the entity is a good path forward. If not, consider caching just the primary key(s) and look up. Of course, that’s not really a lot of data to save when caching, so ¯\_(ツ)_/¯.

1 Like

Thanks Eric! That makes perfect sense.