PHP包含路径CMS

时间:2012-05-29 10:50:59

标签: php content-management-system include-path

我的包含路径有问题。我正在尝试构建一个cms,但我想构建它,以便不是所有文件都需要在包含的根目录中。

Link To File Structure

我试图从任何地方包含到另一个文件。但问题是我将文件包含在其他文件中。

像: 我在T_ErrorLog中包含ErrorHandling 但我在ErrorHandling的Textfiles中使用了一个文本文件,因此路径不正确。

错误:

Notice: Undefined variable: error in C:\Users\Kevin\Desktop\Dropbox\Programming\Webdesign\Workspace\KLJ Peer\GhostCMS\TestFiles\T_ErrorLog.php on line 7
Test

Warning: fopen(/GhostCMS/Textfiles/ErrorLog.txt) [function.fopen]: failed to open stream: No such file or directory in C:\Users\Kevin\Desktop\Dropbox\Programming\Webdesign\Workspace\KLJ Peer\GhostCMS\Core\ErrorHandling.php on line 15
can't open file

T_ErrorLog.php

<?php

include_once ('../Core/ErrorHandling.php');

use Core\ErrorHandling;

ErrorHandling::HandleError("Test", $error);

ErrorHandling.php     

namespace Core;

class ErrorHandling {
    public static function HandleError($errorMessage, $error){
        echo $errorMessage . "<br />";
        echo "Indien dit zicht blijft voor doen.<br />";
        echo "Zal de webmaster dit ontvangen en even kijken naar het probleem!<br />";

        ErrorHandling::WriteToErrorFile($errorMessage, $error);
    }
    public static function WriteToErrorFile($errorMessage, $error){
        $myFile = "/GhostCMS/Textfiles/ErrorLog.txt";
        $fh = fopen($myFile, 'a') or die("can't open file");

        $today = date('j/n/Y - H:i:s');
        fwrite($fh, "Error: \n");
        fwrite($fh, "Date: " . $today . "\n");
        fwrite($fh, "User error message: " . $errorMessage . "\n");
        fwrite($fh, "System error message: " . $error . "\n");
        fwrite($fh, "--------------------------------------------------\n");
        fclose($fh);
    }
}

是否有某种方法可以使目录???的包含路径相对

2 个答案:

答案 0 :(得分:1)

嗯,你知道你的文件结构,它不会真正改变。一般来说,您有几个选项:记录根目录或起点,从哪里派生您的其他文件,包括 DIR FILE PHP Magic Constants <等选项/ p>

e.g。您可以在安装时或在引导程序文件中保存文件,然后只调整目录以从该路径派生。

$myPreviouslySavedPath = __DIR__   // e.g. /home/user/meme/www/
fopen($myPreviouslySavedPath . '/GhostCMS/Textfiles/ErrorLog.txt') // would then be /home/user/meme/www/GhostCMS/Textfiles/ErrorLog.txt 

另外对于php包含php有一个autoloader,它只是你自己提供的一个函数,你可以让函数决定从哪里加载特定文件。 这是您在CMS的入口点设置的内容,可能与您收集的基本目录结合使用。

e.g。

spl_autoload_register('myClassLoader');

function myClassLoader($class){
     // << here you'd place logic to decide the best path for your file >>
     include(__DIR__ . "/classes/$class");
}

要记住和使用的主要事情是您的应用程序有一个固定的入口点,并且您知道该文件的位置。从那里你可以推断出所有其他文件的逻辑路径。

答案 1 :(得分:0)

我建议重写代码,以便不使用include或require,并且可以通过正确设置包含路径来实现此方法 - 请参阅http://php.net/set_include_pathhttp://php.net/get_include_path并使用自动加载器类/函数

然后当'使用'基于命名空间的类时,您的自动加载器将搜索包含路径并尝试包含该文件......

通过这个你可以拥有外部库,类在不同的地方,然后你的CMS,但仍然可以通过自动加载器和命名空间轻松地包含它们......