Moving Preprocess Functions to Separate Files in Drupal 6 & 7

When you implement hook_theme() in Drupal, there is provision to specify the file which should be loaded for the theme functions and preprocess functions to be found. So, we can simplify module file by moving out theme function and preprocess function of our theme entries to separate file. This also has added benefit of reducing module loading. On each bootstrapping Drupal will load every .module file those are of enabled modules. So we should consider moving out code from .module file and also giving modular structure.

Now, consider the scenario of you preprocessing a theme defined by another core or contributed module, and those functions are considerably large. It was a situation I faced recently which required to provide considerable number of preprocess functions for views. It is a project running in Drupal 6 codebase and some of the preprocess functions are 50 to 100 lines of code. Combining all these easily made .module file large. Module was altering theme registry by implementing hook__theme_registry_alter() and adding preprocess functions for views as required.

I thought of moving out these preprocess functions to separate files. But could not find any provision to specify include files for preprocess functions in hook_theme() documentation. When inspected theme function in theme.inc, it could be found that it is trying to load files specified in 'include files' of theme info. So I could move out preprocess functions to separate files and specify the file name in 'include files' option.

What I did would be look like this (for Drupal 6):

function my_module_theme_registry_alter(&$theme_registry) {
  $preprocess_file = drupal_get_path('module', 'my_module') . '/includes/my_module.my_view.inc';
  $theme_registry['my_view_name']['preprocess functions'][] = 'my_module_views_view_my_view_name';
  $theme_registry['my_view_name']['include files'][] = $preprocess_file;
}

For Drupal 7, option name is bit different. We need to use 'includes' instead of 'include files':

function my_module_theme_registry_alter(&$theme_registry) {
  $preprocess_file = drupal_get_path('module', 'my_module') . '/includes/my_module.my_view.inc';
  $theme_registry['my_view_name']['preprocess functions'][] = 'my_module_views_view_my_view_name';
  $theme_registry['my_view_name']['includes'][] = $preprocess_file;
}

I am not sure why this provision was not documented. Anyway, it was very helpful.