我建议你看看
Composer’s Compiler(它最初是由Fabien Potencier在Silex创建的)。在该类中,您可以看到Composer等大型控制台应用程序如何创建.phar文件。
一些有趣的部分:
// line 49
$phar = new \Phar($pharFile, 0, 'composer.phar');
$phar->setSignatureAlgorithm(\Phar::SHA1);
$phar->startBuffering();
// Line 54
$finder = new Finder();
$finder->files()
->ignoreVCS(true)
->name('*.php')
->notName('Compiler.php')
->notName('ClassLoader.php')
->in(__DIR__.'/..')
在这里,Composer使用Symfony2 Finder Component查找src目录中的每个文件(该文件和自动加载机除外)。
// Line 63
foreach ($finder as $file) {
$this->addFile($phar, $file);
}
在这里,Composer遍历每个找到的文件,并将其添加到Phar存档中。 (您可以在line 116看到编译器#addFile方法)。
这重复了一段时间。然后在第93行,使用Composer自动装载机:
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php'));
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php'));
因为Phar是一个流,目录结构保存在phar文件中,Composer自动装载器仍然可以加载类。
然后,最后添加存根并停止缓冲:
$phar->setStub($this->getStub());
$phar->stopBuffering();
(请参阅编译器#getStub方法在line 173)。 Phar#stopBuffering方法停止创建phar并将其保存到phar文件。
为了使此故事完成,Composer创建了一个非常简单的CLI compile file,它运行此命令。