Autoloading classes in drupal 7

When adding a lot of your own classes on top of the Drupal 7 framework you may well want to add your own autoloader. This article looks at the options for including individual files, and how to add a custom autoloader for many files.

Including files

Add to the .info file

Individual files can be included by adding the following into your .info file that lives within your theme folder:

files[] = includes/myfile.php

Load module files with module_load_include()

To include a module file you can use the module_load_include() function which takes the following parameters:

$type - the file extension

$module - the module that the file belongs to

$name - optional parameter to set the base file name without the extension. Without this "$module.$type" is used.

module_load_include('php','mymodule','name');

Good old fashion include or require

Simply add an include or require into the file you wish to use the new class. Both achieve the same result however 'require' will throw a fatal error if the file is not loaded, whereas include will only show a warning.

include_once ('/path/to/file.php');

require_once ('/path/to/file.php');

X autoload plugin

The X autoload plugin allows you to include files in the same manner as you would in Drupal 8 which uses the PSR-0 standard for namespaces. The plugin allows you to register the directories that should be used. 

DIY - Add your own autoloader

In PHP you can easily add an autoloader using the magic function __autoload(). As this function only allows you to have one autoload method, PHP also introduced spl_autoload as of PHP 5.1.2, this makes it possible to have multiple autoloaders. This is important to note in Drupal 7 as spl_autoload will overwrite the __autoload method, meaning if you just add __autoload it won't work due to Drupal 7's existing autoloaders.

By default Drupal has two autoloaders registered in the bootstrap: 

  spl_autoload_register('drupal_autoload_class');

  spl_autoload_register('drupal_autoload_interface');

The class autoloader ends up calling a function _registry_check_code() which checks for a resource in the registry as the name suggests.

To add your own autoloader method simply add this into your template.php file 

spl_autoload_register('autoload');

function autoload($class)

{

    if(file_exists('/path/' . $class . '.php'))
    {
        include('/path/' . $class . '.php');
    }

}

Resources:

http://php.net/manual/en/function.spl-autoload-register.php

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.