Using The Caldera Forms Autoloader


Caldera Forms provides an autoloader. Because of backwards compatibility with PHP 5.2 and Caldera Forms itself, which originally did not use an autoloader, the Caldera Forms autoloader follows no established standard, is limited in features and is kind of weird.

This autoloader is used for Caldera Forms core and for some Caldera Forms add-ons. By convention, Caldera Forms core classes are prefixed with “Caldera_Forms” while add-ons use “CF_{add-on-slug}”. All classes used with this autoloader, must use Caldera_Forms or CF as prefix.

Note from Josh: This is why you should always adopt PSR-4 autoloading from version 0. See my Torque Post.

The autoloader is located at https://github.com/CalderaWP/Caldera-Forms/blob/master/classes/autoloader.php and is used by Caldera Forms in the main plugin file by the function caldera_forms_load().

The caldera_forms_includes_complete fires after the autoloader is loaded and core classes are loaded. Add-ons using the Caldera Forms autoloader should register at or after this action.

Registering An Add-on With The Caldera Forms Autoloader

Note: Many Caldera Forms add-ons use the PSR-4 autoloader provided by Composer. Please ask yourself why you are not doing that before using the Caldera Forms autoloader.

In this example an add-on will use “CF_Roy” as its prefix and located classes in a directory called “classes”. This will allow the class “CF_Roy_Hello” to be autloaded, provided it is located in the file “classes/hello.php”.

Registering A Caldera Forms Core Directory For Autoloading

The method “Caldera_Forms_Autoloader::add_root()” must be used for each directory that is autoloaded from beacuse the autoloader is not sub directory aware. Therefore to add a new directory to Caldera Forms “/classes” you must register that root. If you were adding the class “Caldera_Forms_GraphQL_Post” you would first need to add, inside of the function caldera_forms_load() – Caldera_Forms_Autoloader::add_root( 'Caldera_Forms_GraphQL', CFCORE_PATH . 'classes/graphql' );

 

Where Does This Code Go?

When using WordPress hooks to customize Caldera Forms or other plugins you should not modify the plugin files, or you will lose your changes when you update the plugin. Instead you should create a small plugin to hold the custom code. It's easy, learn how here.

Technically you can add the custom code to your theme's functions.php, but then you will not be able to change your theme and keep these customizations.

Learn More