When using Composer for PHP class autoloading, it is a good practice to wrap your require statement with an is_readable() check. Here are some notes on why this is an important thing to do.
if ( is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
require_once __DIR__ . '/vendor/autoload.php';
}
Your Autoload File Might Not Be There
When you run composer install from within your package directory, the /vendor directory will be added to the package directory and
require_once __DIR__ . '/vendor/autoload.php';
should work just fine.
However, if you load your package as a dependency (i.e. inside a project with a composer.json file at the root of the project), the files will instead be installed to a common /vendor directory in the project, NOT inside your package directory.
In this scenario (where your package is loading as a dependency within a project), the require_once statement above appearing in your package will throw a Fatal Error.
Note: In this scenario where your package is loaded as a dependency in a project, the project code should load its own autoloader to load files from the common /vendor directory.
Why Check Is Readable instead of File Exists
The is_readable() check does a file_exists() check and then checks that the file can be successfully read.
This is important because if the file does exist but the permissions are set such that your PHP code can not read the file, the file_exists() check will pass but when we try to require_once the file, it will fail with a fatal error.
Best Practices
Typically, you want to place the is_readable() / require_once code snippet both in the root file of you package and in the root file of your project.
if ( is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
require_once __DIR__ . '/vendor/autoload.php';
}
Really, Sal? And if it’s not readable, what’s then? The error will magically disappear? So stupid.Translation: In the case where the file is present but the permissions are set such that your PHP code can not read the file, won’t you still get the error?
That’s an interesting point. Then I’m assuming you’re in favor of a
file_exists()check rather than anis_readable()check.I can see that you might prefer in the situation where the file exists but with incorrect permissions would immediately throw a fatal error indicating the problem, while with the
is_readable()check you’d see an error where your autoloaded class was undefined (which I’d argue is also a clear indicator of a problem with the autoloader).I supposed
is_readable()would have the advantage in the rare case where both autoloaders are present (both in the root file of you package and in the root file of your project) but that seems like an error state anyway.Based on all of this, I can see why you might choose to use
file_exists()overis_readable().