Autoloading PHP Classes on Windows OS correctly

on in Tutorials | 2 min read
Site icon rtCamp

Autoloading PHP Classes on Windows OS correctly

A few weeks ago, we released WP Menu Custom Fields plugin which utilizes custom menu fields API added in WordPress 5.4 around the same time.

Recently, we received a bug report that our plugin was causing a fatal error in their local development environment. The error details provided by the user indicated a file required by the plugin was not being found.

I knew that we tested our plugin with the LEMP/LAMP/MAMP stacks pre-release, so this had to be caused by the user’s Windows development environment.

So I started debugging the issue, beginning at the most logical place – the autoloader. This piece of code enables any PHP class to be called from across the codebase without having to require or include each class manually.

When our plugin is initialized, the autoloader constructs a namespace and ensures that every file within it is accessible and valid using the standard WordPress function validate_file():

$resource_path = 'path/to/the/file';

if ( ! empty( $resource_path ) && file_exists( $resource_path ) && 0 === validate_file( $resource_path ) ) {
	require_once $resource_path;
}

validate_file() returns 0 when it detects that all files exist and are valid. However, this is only true for UNIX-like file paths and not Windows drive paths, as described in its documentation:

Source: WordPress Code Reference docs

Since our code assumed that “0 means nothing is wrong, greater than 0 means something was wrong”, it threw a fatal error on the user’s Windows machine. A little tweaking and the code works just as expected on Windows: 👍

$resource_path = 'path/to/the/file';

$resource_path_valid = validate_file( $resource_path );

if ( ! empty( $resource_path ) && file_exists( $resource_path ) && ( 0 === $resource_path_valid || 2 === $resource_path_valid ) ) {
	require_once( $resource_path );
}

This little incident was an excellent reminder of the importance of questioning our assumptions or risk losing touch with reality.

“Your assumptions are your windows on the world. Scrub them off every once in a while, or the light won’t come in.”

Isaac Asimov

Links: WP Menu Custom Fields Plugin | Work with us


Exit mobile version