All Posts

Externalizing long configuration arrays post

While re-writing Field Class Registration for Ninja Forms 3.0, one of my goals was to clean up the file structure for adding fields. Previously, in Ninja Forms 2.*, new fields were created with procedural PHP, long argument arrays, and prefixed WordPress action hooks. These files were large, messy, and a burden to maintain. As a part of the re-write process, we were able to step back and take a fresh approach for registering new form fields with the Ninja Forms drag-and-drop form builder.

Instead of building large arguments arrays, passing them through a function for registration, and cramming these arrays into the same files as the functionality, fields are now organized into classes with properties and external configuration arrays for settings. The previous method required 100 lines of code just for defining settings. As an example, the simple textbox field registration file was 353 lines long. Compared to the current re-write, the textbox field registration file is only 36 lines long. By the time we ship, I would expect that any field's registration class never be more than 100 lines of code per file.

[caption id="attachment_577" align="aligncenter" width="1024"][Field Class Registration in Ninja Forms Left: Single $args array. Right: Class with Properties[/caption]

Of course removing content from a file reduces an individual file size, and this removed content does need to go somewhere. So the question remains, what to do with these long configuration arrays?

Looking at the Laravel PHP Framework, you will see many folders of configuration files. The framework is very flexible and these externalized configuration files allow for easy reference and maintenance.

In any PHP application, externalized configuration arrays can be included into a variable or property with the include statement. The configuration array is stored in a separate file following a return statement. Upon including the file, the value of the array is returned and can be assigned to a variable or property. Below is an example of how this works in practice:


We are still very early in the re-write process, but here is what we have now for simple field registration:

[caption id="attachment_592" align="aligncenter" width="1024"]Left: [Field Registration](, Right: [Config File]( Left: Field Registration, Right: Config File[/caption]