使用php获取父文件夹路径
我正在开发我的第一个 MVC 框架,并且想要为 BASE_PATH、APP_PATH、LIB_PATH 和 LIB_PATH 定义 4 个常量。公共路径。我的文件结构如下所示:
/
/app
/controllers
/models
/views
/config
/db
/lib
/public_html
/css
/js
/img
我的 index.php 文件位于 public_html 目录中。目前有以下代码:
error_reporting(E_ALL);
define('BASE_PATH',dirname(realpath(__FILE__)) . "/../");
define('APP_PATH',dirname(realpath(__FILE__)) . "/../app/");
define('LIB_PATH',dirname(realpath(__FILE__)) . "/../lib/");
define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");
require LIB_PATH . 'core.php';
这可行,但我觉得必须有更好的方法来做到这一点,而无需所有“..”。有什么建议或者这是最好的方法吗?让我知道。谢谢你!
答案
感谢@fireeyedboy和@KingCrunch,我已经找到了我一直在寻找的解决方案。这是我的最终代码:
define('PUBLIC_PATH', dirname(__FILE__) . "/");
define('BASE_PATH', dirname(PUBLIC_PATH) . "/");
define('APP_PATH', BASE_PATH . "app/");
define('LIB_PATH', BASE_PATH . "lib/");
I am working on my first MVC framework, and want to define 4 constants for BASE_PATH, APP_PATH, LIB_PATH & PUBLIC_PATH. My file structure looks like this:
/
/app
/controllers
/models
/views
/config
/db
/lib
/public_html
/css
/js
/img
My index.php file is located in the public_html directory. And currently has the following code:
error_reporting(E_ALL);
define('BASE_PATH',dirname(realpath(__FILE__)) . "/../");
define('APP_PATH',dirname(realpath(__FILE__)) . "/../app/");
define('LIB_PATH',dirname(realpath(__FILE__)) . "/../lib/");
define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");
require LIB_PATH . 'core.php';
This works, but I feel like there must be a better way of doing it without all of the "..". Any suggestions or is this the best way of going about it? Let me know. Thank you!
ANSWER
Thank you to @fireeyedboy and @KingCrunch, I have come up with the solution I was looking for. This is my final code:
define('PUBLIC_PATH', dirname(__FILE__) . "/");
define('BASE_PATH', dirname(PUBLIC_PATH) . "/");
define('APP_PATH', BASE_PATH . "app/");
define('LIB_PATH', BASE_PATH . "lib/");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
换句话说,再次使用
dirname()
。并重新排序定义常量以直接使用它们。但不确定它是否有助于可读性。How about this:
In other words use
dirname()
again. And re-order defining the constants to make direct use of them. Not sure it helps readability though.首先:
只是没用
但是,没有“真正的”更好的方法,因为
../
并不“脏”。我想到的唯一的其他解决方案..
是文件系统(它不是由 php 发明的;))定义其父目录的方式,就像.
定义的那样当前目录。First:
is just useless
However, there no "real" better way, because
../
is not "dirty". The only other solution, that comes in my mind..
is the way a filesystem (its not invented by php ;)) defines its parent directory, just as well.
defines the current directory.这不应该在index.php中..它应该在config/文件夹中,并且PUBLIC_PATH与BASE_PATH相同...而且我不喜欢使用dirname和realpath函数,我只是写正确的手动路径(但这只是我)
this shouldn't be in the index.php.. it should be in the config/ folder and the PUBLIC_PATH is the same as the BASE_PATH... And i don't like using the dirname and realpath function, i just write the correct path manually (but that's just me)