douying1119 2016-05-23 03:15
浏览 214
已采纳

如何在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条回答 默认 最新

  • dsgfdgh14569 2016-05-23 04:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题