如何在Yii2中require_once一个文件,它位于我的目录树中比应用程序根目录更高的位置?

如何在Yii2中require_once一个文件,它位于我的目录树中比应用程序根目录更高的位置?

问题描述:

Yii2 has no problem addressing namespaces outside of the active application directory tree. However I would like to use a require_once statement to get a file holding just constants (i.e., a long list of define(CONSTANT, value) statements) from a location that both the frontend and backend Yii2 advanced template application instances can share.

Right now I am using:

require_once '..\..\common\config\keywords.php';

but this fails when I migrate my application from the Windows development environment in which I am working to the Linux environment where it runs in production, possibly because the relative addressing prefix ('..\..\') isn't something Linux can interpret (?).

Ideally I would like a solution that uses an alias or in some way does not depend on relative or absolute paths. But while this works to include the file when it is located under the base application path:

require_once Yii::$app->basePath.'\config\keywords.php';

.. it still doesn't give me a way to address a directory from a starting point higher than the application base path.

This seems like a common problem that anyone trying to use a shared file of constants would have. How do experts solve it? Am I missing a more elegant approach?

1) If you want to use directory paths explicitly:

Windows understands both / and \ slashes, while Linux and other OS - /. Keep that in mind when constructing paths. So use / instead.

Sometimes it's more flexible to use special predefined PHP constant DIRECTORY_SEPARATOR. Concatenate it with folder names and you get platform indepedent path.

2) Other option is avoid using paths explicitly. Create component (helper class, for example ConstantsSetter) with method that do all the stuff you need, add namespace to it (for example common\components), then execute it during application bootstrap. You can directly add call to a bootstrap.php file (see this related answer) or use yii\base\BoostrapInterface.