PHP依赖和类路径管理

时间:2012-10-11 15:39:27

标签: php dependencies classpath

我经常遇到的一件事是我在PHP中没有类路径和依赖管理系统。你能建议一个框架吗?我听说Pear是一个很好的系统,但是我想知道还有什么。

一个例子就是说...我有文件A.php,B.php和C.php,其中A依赖于B依赖于C.其中所有3个都在不同的文件夹中。

因此,一旦A.php包含B.php,它还需要包含C.php。在B.php中输入require_once(“C.php”)是行不通的,因为require_once必须调用A.php和C.php之间的相对路径,而不是B.php和C.php之间的相对路径,这很烦人。 / p>

3 个答案:

答案 0 :(得分: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];
    }
}

还有很多可以做到这一点,即安全检查各种事情,例如在构建自动加载列表时找到的重复类,确保文件存在然后再尝试包含它们等等。

答案 1 :(得分:2)

我建议你尝试一下doctrine类加载器项目。

Here您可以找到官方文档。

要使用此库,您需要一个具有名称空间支持的php版本(然后&gt; = 5.3)

答案 2 :(得分:1)

Composer就是它的全部,它可以很方便地为你完成所有这些

http://getcomposer.org/

相关问题