繁体   English   中英

PHP项目中配置文件的相对路径

[英]Relative path to config file in PHP project

我是PHP新手。 我正在开发一个新的PHP网站。 我的网站文件夹结构如下

-SystemRoot
    +Code
    +Data_Access
    -Public_HTML
        +css
        +js
        +Templates
    -resources
        config.php

我在资源目录中有一个配置文件,我需要在各种目录中的大多数其他php页面中包含config.php 所以我必须在不同的页面中以不同的方式指定配置文件的路径,例如,

include_once '../resources/config.php';
include_once '../../resources/config.php';

有没有一种方法可以克服这个问题,并使用通用(相对)路径到config.php ,该路径可以在项目中的eny文件夹路径中使用?

在php项目中包含类的常见/最佳实践是什么?

除了您的require()的执行方式不同之外,我几乎完成了您过去的操作:

require_once(str_replace('//','/',dirname(__FILE__).'/') .'../../config.php');

然后,我定义可以在整个过程中使用的其他路径,如下所示:

// DIRECTORY_SEPARATOR is a PHP pre-defined constant
// (\ for Windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);

// Define Views URL path
defined('VIEW_URL') ? null : define('VIEW_URL', '/application/views');

// Define CSS URL path
defined('CSS_URL') ? null : define('CSS_URL', '/public/css');

// Define JavaScripts URL path
defined('JS_URL') ? null : define('JS_URL', '/public/js');

// Define site root
defined('SITE_ROOT') ? null : 
  define('SITE_ROOT', str_replace('//','/',dirname(__FILE__)));

// Define App path as 'application' directory
defined('APP_PATH') ? null : define('APP_PATH', SITE_ROOT.DS.'application');

// Define Includes path as 'application/includes' directory
defined('INC_PATH') ? null : define('INC_PATH', APP_PATH.DS.'includes');

// Define Helpers path as 'application/helpers' directory
defined('HELP_PATH') ? null : define('HELP_PATH', APP_PATH.DS.'helpers');

// Define Controllers path as 'includes/classes' directory
defined('CTLR_PATH') ? null : define('CTLR_PATH', APP_PATH.DS.'controllers');

// Define Models path as 'includes/classes' directory
defined('MOD_PATH') ? null : define('MOD_PATH', APP_PATH.DS.'models');

// Define Views path as 'includes/classes' directory
defined('VIEW_PATH') ? null : define('VIEW_PATH', APP_PATH.DS.'views');

chdir($_SERVER['DOCUMENT_ROOT']);开始脚本chdir($_SERVER['DOCUMENT_ROOT']); 从那里开始,所有include和所有其他文件功能(例如file_existsfopen等)都将从网站的根目录(通常为public_html )运行。

您可以将所有内容路由到index.php

然后定义一些常数。 路由到index.php的Evrything将可以访问它们。

define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

define('RESOURCES', SELF . 'resources/');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM