Share via:

Including Files in PHP via BASE_PATH

How we currently handle includes and writing of paths in code.

37 views

Edited: 2019-08-11 17:47

When including files in Beamtic's PHP projects, we are currently using absolute paths with a defined BASE_PATH, and forward slash as directory separator.

This means all paths should be written using forward slash, since this is supported by most systems.

Windows will also work just fine using forward slash, and even using a mix of backslash and forward slash should work fine. For consistency, it is best we use the same throughout the code.

Another reason for this policy is that backslash might cause problems in some circumstances, since it has special meaning in PHP, and therefore needs to be escaped when used in paths, even when used within single quotes..

Handling includes

At the top of an index file we usually define a BASE_PATH constant. This constant can be used when including files via include or require, and can also be accessed from within the included files, though this is best avoided.

If some class methods depends on BASE_PATH, it is probably better to pass it as an argument to the method, or via dependency injection through a settings object.

Below is an example of how BASE_PATH is defined:

define('BASE_PATH', rtrim(preg_replace('#[/\\\\]{1}#', '/', realpath(dirname(__FILE__))), '/') . '/');

The code works like this:

  1. realpath(dirname(__FILE__)) creates the absolute path for the parent directory of the running script.
  2. preg_replace makes sure we only use forward slash as separator. Note. Backlash needs to be escaped like this "\\\\" when used in regular expressions.
  3. rtrim() removes a trailing slash (if any).
  4. Finally a trailing slash is added manually. This is needed to avoid confusion when using the BASE_PATH constant.

Dynamically including files

Currently developers need to remember using forward slash consistently. This is not a huge problem since most will probably be developing on Linux anyway. But, a solution could be to include files via a function or asset loader instead.

This is not something we are currently doing, but it would also be a useful way to dynamically include files if this is something we might need in the future.

$files_to_include = array(
  BASE_PATH . 'lib/db_class/db_class.php',
  BASE_PATH . 'lib/translator/translator_class.php'
);

function dynamic_require($files_array) {
  foreach ($files_array as $file) {
   require preg_replace('#[/\\\\]{1}#', '/', $file);
  }
}

DIRECTORY_SEPARATOR is not recommended

It is not recommended that developers use DIRECTORY_SEPARATOR, since most systems will understand forward slash just fine. There might still be niche cases where it can be useful, but we avoid it for includes.

DIRECTORY_SEPARATOR is a predefined constant in PHP. It contains the default directory separator used on the system where the script is running.

Comments