0

经常困扰我的一件事是我在 PHP 中没有类路径和依赖项管理系统。有没有可以推荐的框架?我听说 Pear 是一个很好的研究系统,但我想知道还有什么。

举个例子……我有文件 A.php、B.php 和 C.php,其中 A 依赖于 B,而 B 又依赖于 C。这三个文件都位于不同的文件夹中。

所以一旦A.php包含了B.php,它也需要包含C.php。在 B.php 中键入 require_once("C.php") 不起作用,因为 require_once 必须调用 A.php 和 C.php 之间的相对路径,而不是 B.php 和 C.php 之间的相对路径,这很烦人。

4

3 回答 3

3

对于这个问题,我倾向于使用自动加载器。制作一个健壮的脚本来扫描一些给定的文件并构建一个映射到文件的类列表并不难。这是我的做法:

$classes = array();

//this is the main function, give it a file and it will map any
//classes it finds in the file to the path. How you find the files
//is up to you, only you know your directory structure, but I
//generally set up a few folders that hold my classes, and have
//the script recurse through those passing each file it finds through
//this function
function get_php_classes($file) {
    global $classes;
    $php_code = file_get_contents($file);
    $tokens = token_get_all($php_code);
    $count = count($tokens);

    //uses phps own parsing to figure out classes
    //this has the advantage of being able to find
    //multiple classes contained in one file
    for ($i = 2; $i < $count; $i++) {
        if (   $tokens[$i - 2][0] == T_CLASS
            && $tokens[$i - 1][0] == T_WHITESPACE
            && $tokens[$i][0] == T_STRING) {

            $class_name = $tokens[$i][1];
            //now we map a class to a file ie 'Autoloader' => 'C:\project\Autoloader.cls.php'
            $classes[$class_name] = $file;
        }
    }
}

$fh = fopen('file_you_want_write_map_to', 'w');
fwrite($fh, serialize($classes));
fclose($fh);

那是生成文件映射的脚本,您在添加新类时运行一次。以下是可用于自动加载的实际应用程序代码:

class Autoloader {
    private $class_map;

    public function __construct() {

        //you could also move this out of the class and pass it in as a param
        $this->class_map = unserialize(file_get_contents($file_you_wrote_to_earlier));
        spl_autoload_register(array($this, 'load'));
    }

    private function load($className) {
        //and now that we did all that work in the script, we
        //we just look up the name in the map and get the file
        //it is found in
        include $this->class_map[$className];
    }
}

可以做的还有很多,即安全检查各种事情,例如在构建自动加载列表时发现的重复类,在尝试包含它们之前确保文件存在等。

于 2012-10-11T17:28:01.380 回答
2

我建议你试试学说类加载器项目。

在这里你可以找到官方文档。

为了使用这个库,你需要一个支持命名空间的 php 版本(然后 >= 5.3)

于 2012-10-11T15:53:06.373 回答
1

Composer 是一切的发源地,它可以轻松地为您完成这一切

http://getcomposer.org/

于 2012-10-11T22:49:54.927 回答