以下是我的目录列表:
>htdocs
-->MyWeb
---->admin
------>cms.php
---->images
---->controller
------>post.php
------>general.php
---->model
------>posts.php
------>sessions.php
------>connections.php
---->index.php
,下面是每页从上到下的内容:
cms.php:
require_once('../model/sessions.php');
require_once('../controller/post.php');
post.php:
require_once('general.php');
require_once('../model/posts.php');
general.php : none
posts.php:
require_once('sessions.php');
require_once('connections.php');
sessions.php:
require_once('connections.php');
connections.php : none
index.php:
require_once('controller/post.php');
condition:用cms.php测试了一切,我使用控制器提供的表单访问了所有的函数,控制器从模型中获得了数据。现在,管理工作完成了,该到index。php中显示数据了,我把它放到index。php中,打开后,结果如下:
我得到了错误,告诉我"require_once()"函数无法找到指定的文件。我用cms。php做了这个,没问题。错误不是来自index.php,而是来自
让我们再看看index.php,它已经包含了控制器,post.php使用"require_once('controller/post.php');",但post控制器本身,包括另一个文件,这是post模型"require_once('../model/posts.php')"。当index.php使用顶部文件夹透视图 (MyWeb)查看控制器所需的文件,然后读取包含的文件时,就会出现问题在post controller中,正好是"require_once('../model/posts.php')"= index.php的一个文件夹,文件夹模型,这意味着:
htdocs>model>posts.php当然是不存在的。我第一次真的很困惑,然后我为此创建了一些作弊方法:
1. I put a variable $check = true ; before the require_once('controller/post.php') ; in index.php
2. then for each page that requires another file, i put these :
//for example, in sessions.php
if(isset($check)) {
//old link which is like this : require_once('connections.php') ; has become :
require_once('model/connections.php') ;
//so in index.php perspective, the file can be reached
}
else {
//old links, only executed when this page was not viewed from index.php
require_once('connections.php') ;
}
3. it works now, cms.php read the includes from old links, while index.php will read the included from new links.
现在,即使它工作,我的代码看起来丑陋和不一致,如果在未来,我可能会添加更多的文件,更多的包含。有人有更好的解决方案吗?如何访问应用程序的工作目录,例如在Linux中使用:~/controller/post.php或~/model/posts.php。所以地址是一致的。不能使用getcwd(),我不想显示文件的绝对路径。有没有人能给我更好的解决方案来指定目录,如我的情况?
注意:不好意思
如何访问应用程序的工作目录,例如在Linux中使用:~/controller/post.php或~/model/posts.php。
$_SERVER['DOCUMENT_ROOT']
DOCUMENT_ROOT
可以工作,但如果您需要能够在子目录(如
domain.com/apps/myapp
domain.com/apps/myapp/v1
在这种情况下,我最喜欢的方法是在每个脚本中调用的配置文件中定义根目录:
// in /index.php
define("BASEDIR", dirname(__FILE__));
您可以在任何需要替换应用程序的完整路径的地方使用BASEDIR
常量。