问题
I have been all over the Internet trying to figure out the best way to handle paths in my website. Should I use relative paths, absolute paths?
I have seen dirname (FILE) mentioned several times. One problem I have with relative paths is that PHP files which are included by several other files at different directory levels cause the relative paths to break. For example if the directory structure is
Root
A
B
b
And a PHP file in b and An include another file from B then the relative paths for the code in the file in B will be different.
So in general what is the best way to handle paths to files with regards to includes and file operations within the code.
回答1:
Tho there are many ways to find out the path I always find it easiest to define a constant within a file on the root of the project index.php
or a config
of sort.
then I can use SITE_ROOT
for includes/class loaders ect, and SITE_URL
for views, controllers, redirects ect.
<?php
$root=pathinfo($_SERVER['SCRIPT_FILENAME']);
define ('BASE_FOLDER', basename($root['dirname']));
define ('SITE_ROOT', realpath(dirname(__FILE__)));
define ('SITE_URL', 'http://'.$_SERVER['HTTP_HOST'].'/'.BASE_FOLDER);
?>
Basic class Autoloader
<?php
function __autoload($class_name) {
include (SITE_ROOT.'/includes/'.$class_name.'.php');
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
回答2:
You could put all your include files into one main directory. Then create a path variable in a config file or in the script itself, which points to the include directory.
回答3:
The best way to use proper naming conventions for the Directory Structure, PHP files and Class names of the file and the design a autoloader to include the file
回答4:
The Zend framework has some good pointers about optimizing include paths:
http://framework.zend.com/manual/1.10/en/performance.classloading.html
Even if you're not using the Zend framework, these are good pointers. The general bulletpoints are:
- Use absolute paths
- Reduce the number of include paths you define
- Define the current directory last, or not at all
- Define your Zend Framework include_path as early as possible (not really relevant if you don't use Zend)
回答5:
New version of php (PHP5.3) is possible to use __autoload So, you just need to determine root of your application.
来源:https://stackoverflow.com/questions/10424963/best-practice-for-php-paths