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 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)