Fragmented Thought

Loading Drupal Core Include Files

The Right Way

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Maybe it's because I've done more with Drupal that's off the map... Or maybe I just dug further than others, but I've noticed way too many developers giving poor advice when it comes to loading the core include files. Allow me to correct that issue for you, and more importantly explain why you need to do it the right way.

Let's start with a basic google, I"m sure that's what most of us do, right? "drupal load core include".

Results (as of this post): The top 4 were drupal.org links

  • https://api.drupal.org/api/drupal/includes%21module.inc/function/module_load_include/7
  • https://api.drupal.org/api/drupal/includes!module.inc/7
  • And a couple other similar documentation style posts.

Next up as expected was stackoverflow: http://drupal.stackexchange.com/questions/95716/how-to-load-an-include-file-from-drupals-include-folder

The OP suggested doing this, with idea that there is a better way:

include(DRUPAL_ROOT."/includes/locale.inc");

Others suggested this is better:

module_load_include('inc', 'content', 'includes/actions');

But, that's actually worse. The OP's suggestion was close to what the core does. The includes in the core are meant to exist without the rest of the Drupal modules. They are independent little gems. So if you're going through module code at all to get to them, you're going the long way.

So, you do have to require them! But, there's more to it than that. If you take the time to dig into the bootstrap.inc file's drupal_bootstrap file, you'll find it loads include like this, and this is the way you have to do it too:

require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');

The file name... is in a variable?! YEP! That's because it's possible to override the core files of Drupal by specifying new locations for those files in settings.php. Why would you do that? Most of the time, it's for custom logic that adjusts, but doesn't break the core. Like adding a new hook into some previously unreachable process. An example in the wild that comes immediately to mind is the module memcache, that allows the cache tables to be stored in high performance memcache tables.

You never know what you, or another developer has done. Take the little extra time to ensure you always match what the core does!