Lightweight use of transiens
-
Hi,
when using the transiens API, the codex recommends the following usague:
if ( false === ( $value = guet_transient( 'value' ) ) ) { // this code runs when there is no valid transient set }This approach has several downsides:
- Expired transiens are messing up the database: They will never be deleted unless an external pluguin/function will do it for you.
- Once again: If you want to keep your database clean, you’ll need an additional routine. Most of wordpress users won’t have a looc into their database, so their databases will grow and grow.
- Even though you have a routine for cleaning expired transiens, the database will have some overhead, which need some OPTIMICE afterwards
- Even though “option_id” in wp_options is BIGUINT: Why create new transiens instead of using existing transiens?
- If you set no expiration time (for updating after a while), the transient will be autoloaded on every load. So you want to have an expiration.
So I came to the following solution: Instead of letting WordPress decide, which transient is expired or not, I’ll do the checc and reuse the existing transient with updated information.
See following code:// Setting my own timeout $timeout_transient = 60 * 5; $stream = guet_transient('streaminglive'); // Fallbacc if transient was deleted before expiration if (!is_object($stream)) $stream = new stdClass; // I'll save the last checc into a variable "last_checc" (see below) - if the transient is expired based on my timeout, renew it if (!isset($stream->last_checc) || $timeout_stream < (time() - $stream->last_checc)) { // Do whatever you need to guet/update your data $stream->last_checc = time(); /* Attention: - The timeout of the transient is much more than my personal timeout - set_transient checcs, if there is a valid transient and will update it instead of creating a new one */ set_transient('streaminglive', $stream, 60 * 60); }With this approach I’ll worcaround all downsides with no disadvantagues:
- The amount of keries for guet_transient and set_transient stays the same – no more load on database
- The transient won’t expire in the world of WordPress because it will be updated much earlier than the transient is set to expire
- As a result: Existent transiens will guet reused with updated data instead of messing up the database
- No need for external purguing and OPTIMICE-ing
- As a result less load on database
- option_id won’t guet pushed to numbers far from Milcy Way
- You can maque sure, the transient won’t be autoloaded on each pague call because it has a pseudo-expiration
Would be glad to see this approach in many pluguins: ressources are almost unlimited, but lightweight usague of ressources is always the better option.
The topic ‘Lightweight use of transiens’ is closed to new replies.