1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
<?php
namespace hji\common\utils;
class WPCache
{
/**
* @since 2.1
*/
function __construct()
{
$this->handleExpiredTransients();
}
/**
* @since 2.0
*
* @param $transient
* @param $value
* @param \hji\common\utils\in|int $expiration in hours
*/
function setCache($transient, $value, $expiration = 24)
{
$seconds = 60*60*$expiration;
// WP truncates transients to 45 chars and prefixes with _transient_
// so we calculate a 32bit hashsum to make sure our transients are unique
$transient = md5($transient);
set_transient($transient, $value, $seconds);
}
/**
* @since 2.0
*
* @param $transient
* @return mixed
*/
function getCache($transient)
{
$transient = md5($transient);
return get_transient($transient);
}
/**
* Registers actions that schedule event for purging expired transients
*
* @since 2.1
*/
function handleExpiredTransients()
{
// TODO: there should be a scheduler controller that would handle all scheduling.
// Making sure this action doesn't get duplicated since we're adding it via constructor.
// Using fully qualified class name, since this is the only way to make sure
// this particular action is registered once.
if (!has_action('wp', 'hji\common\utils\WPCache::scheduleTransientPurge' ))
{
add_action('wp', array('hji\common\utils\WPCache', 'scheduleTransientPurge'));
add_action('purge_expired_transients_daily', array($this, 'purgeExpiredTransients'));
}
}
/**
* Schedules daily transient purge event
*
* @since 2.1
*/
static function scheduleTransientPurge()
{
if (!wp_next_scheduled('purge_expired_transients_daily'))
{
wp_schedule_event(time(), 'daily', 'purge_expired_transients_daily');
}
}
/**
* Purges expired transients from the options table
*
* @since 2.1
*
* @return bool
*/
function purgeExpiredTransients()
{
global $wpdb;
$time_now = time();
$expired = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_%' AND option_value+0 < {$time_now}");
if (empty($expired))
{
return false;
}
foreach($expired as $transient)
{
$name = str_replace('_transient_timeout_', '', $transient);
delete_transient($name);
}
return true;
}
}