Loading Drupal Core Include Files (The Right Way)

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
And a couple other similar documentation style posts.

Next up as expected was stackoverflow:
The OP suggested doing this, with idea that there is a better way:

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

Others suggested this is better:
  1. module_load_include('inc', 'content', 'includes/actions');

But, that's actually worse. The OP's suggest 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:

  1. 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!



beautiful solution, thank you!

Thanks for you post that helps gaining new knowledge. Respectively, I have a thought that I need to share with you.
I think the only reason for bootstrap.inc file to load "include" files with "require_once" is that "module_load_include" isn't declared yet.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.