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';
}
Leave a Reply