0

我已经在互联网的尽头搜索了这个问题的答案,我即将得出一个合乎逻辑的结论,即这是不可能的。当包含在不同目录/级别中具有其他多个文件依赖于它的文件时,究竟是如何使用相对根?

例如,这是我网站的简化树:

 Main site (PHP reports the main root to be: /Users/Luke/Sites/)
 -> index.php
 -> directoryfolder - > secondaryindex.php

 -> templates -> header.php 
              -> navigation.php

即,如果要在Finder 中导航到index.php,他们会看到目录为/Users/Luke/Sites/SiteAlpha/index.php。

index.php 和 directoryfolder/secondaryindex.php 都包含 header.php,然后包含 navigation.php。问题似乎是,无论我在 header.php 上命名 navigation.php 的包含位置,它都只会允许一个页面正确显示它。IE:

如果在 index.php 上调用 navigation.php(通过 header.php),包含位置为 ROOT_PATH.'/templates/navigation.php(其中 ROOT_PATH 等于 dirname( __DIR__)),它根本不会显示。但它适用secondaryindex.php。

反之亦然。如果在 index.php 上调用 navigation.php(通过 header.php),包含位置为 ROOT_PATH.'/siteAlpha/templates/navigation.php,它实际上会工作。但是它不适用于secondaryindex.php。

TL;DR,由于 header.php 被不同目录级别的多个页面调用,navigation.php 的包含必须同时是我的第一个示例和我的第二个示例。

我尝试使用我自己定义的根常量 $_SERVER['DOCUMENT_ROOT'], dirname( __DIR__), __FILE__,但没有任何成功。我已经阅读了无数文章和 SO 问题,但没有任何帮助。它只是行不通。

有人可以给我一个 ELI5 解释,说明我需要做什么才能使其正常工作吗?

4

1 回答 1

1

首先,我确信一个应用程序应该只有一个入口点。根据您的情况,如果设置了特定参数,您可以在 index.php 中包含 secondayrindex.php。与模板类似的情况:构建一个包含navigation.php 和header.php 的模板。然后你必须只包含单个模板。或者使用像 smarty 这样的模板引擎,它为你做了很多工作(躲起来请不要打我,模板引擎的仇恨者)

回到你的情况。我为您看到了一些可能的解决方案:

  • 在入口点文件中使用应用程序的根目录定义一个常量(例如 index.php - 最适合我的想法是只有一个入口点)
    • 在 index.php 中可能是define('APP_ROOT', __DIR__)
    • 在 secondaryindex.php 中可能是define('APP_ROOT', dirname(__DIR__))
    • Of course you must be aware of not including index.php and secondaryindex.php at the same time
  • use only relative paths
    • Including navigation.php in header.php would be require('navigation.php')
    • Including header.php in index.php would be require('templates' . DIRECTORY_SEPARATOR . 'header.php')
    • Including header.php in secondaryindex.php would be require('..' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'header.php')

Btw: Think of doing sth like this: define('DS', DIRECTORY_SEPARATOR) - writing DIRECTORY_SEPARATOR will drive you crazy.

I'm currently in the stage of using absolute paths only while defining a root directory constant at the entry point or a file included into the entry point which defines all necessary constants.

Hope this could help.

于 2013-02-20T11:10:47.013 回答