Skip to content

Instantly share code, notes, and snippets.

@grayside
Last active December 10, 2015 01:09
Show Gist options
  • Save grayside/4356381 to your computer and use it in GitHub Desktop.
Save grayside/4356381 to your computer and use it in GitHub Desktop.
Brainstorming a Drupal Drush Command to facilitate cache warming after site deployment. Rename to warm.drush.inc for actual use.
<?php
/**
* @file
* Command definition for Drush Cache Warm.
*/
/**
* Implements hook_drush_command().
*/
function warm_drush_command() {
$items = array();
$items['warm'] = array(
'description' => 'Warm the caches so a first-time user after deploy has an lighter load.',
'aliases' => array('cache-warm', 'cw'),
);
return $items;
}
/**
* Command callback for 'warm'.
*/
function drush_warm() {
$data = array('Site Frontpage Request Time' => warm_url('<front>'));
$data = warm_invoke_all('warm_cache') + $data;
if (drush_get_context('DRUSH_VERBOSE')) {
$data['Total'] = array_reduce($data, function($result, $item) {
return $result + $item;
}) . 'ms';
if (drush_get_option('pipe', FALSE)) {
drush_print_pipe(_core_site_credential_list($data));
}
else {
drush_print_table(drush_key_value_to_array_table($data));
}
}
drush_log('Caches have been warmed.', 'success');
}
/**
* Implements hook_drush_help_alter().
*/
function warm_drush_help_alter(&$command) {
if ($command['command'] == 'cache-clear') {
$command['options']['warm'] = 'Warm the cache on completion of cache-clear.';
}
}
/**
* Implements drush_hook_post_COMMAND() for 'cache-clear'.
*/
function drush_warm_post_cache_command_clear() {
if (drush_get_option('warm', FALSE)) {
drush_warm();
}
}
/**
* Retrieve the time it takes to get a page.
*/
function warm_url($path = '<front>') {
$url = call_user_func_array('url', func_get_args());
timer_start('warm-step');
drupal_http_request($url);
$time = timer_read('warm-step');
return $time . 'ms';
}
/**
* Customized version of module_invoke_all().
*
* This function discards all returned data from hook implementations, instead
* providing data on the run time of each implementation run-time.
*/
function warm_invoke_all($hook) {
$args = func_get_args();
// Remove $hook from the arguments.
unset($args[0]);
$return = array();
foreach (module_implements($hook) as $module) {
$function = $module . '_' . $hook;
if (function_exists($function)) {
timer_start('warm-step');
call_user_func_array($function, $args);
$time = timer_read('warm-step') . 'ms';
$return[$function . '()'] = $time;
}
}
return $return;
}
/// Implementations ///
/**
* Implements hook_warm_cache().
*/
function views_warm_cache() {
views_get_all_views();
}
/**
* Implements hook_warm_cache().
*/
function content_warm_cache() {
_content_type_info();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment