我目前正在尝试打包库代码,然后将其发送给实际尝试使用该库代码的人。创建 PHAR 文件后,我试图用一个简单的测试脚本验证它是否正确完成。在 create-PHAR -> use-PHAR 过程中的某个时刻,我做错了什么。
我如何正确创建然后需要 PHAR 文件?
为了简化 PHAR 的制作和验证,我已将所有内容限制为问题的简化版本,但仍然无法继续。
这是我的文件:
~/phar-creation-and-require-test/
mylibrary.php
testoflibrary.php
make-phar.php
make-phar.sh
mylibrary.phar (after being created)
mylibrary.php
内容:
<?
class FooClass {
private $foonum;
function FooClass() {
$this->foonum = 42;
}
}
?>
make-phar.php
内容:
<?php
if ($argc < 3) {
print 'You must specify files to package!';
exit(1);
}
$output_file = $argv[1];
$project_path = './';
$input_files = array_slice($argv, 2);
$phar = new Phar($output_file);
foreach ($input_files as &$input_file) {
$phar->addFile($project_path, $input_file);
}
$phar->setDefaultStub('mylibrary.php');
由 make-phar.sh
调用:
#!/usr/bin/env bash
rm mylibrary.phar
php --define phar.readonly=0 ./make-phar.php mylibrary.phar \
phar-index.php
我可以运行 make-phar.sh
而不会出现任何错误,并且 mylibrary.phar
已创建。
测试脚本 testoflibrary.php
是这样的:
<?php
require_once 'phar://' . __DIR__ . '/mylibrary.phar'; // This doesn't work.
//require_once 'mylibrary.php'; // This would work, if un-commented.
$foo = new FooClass();
print_r($foo);
当我用 php testoflibrary.php
运行它时,我得到这个错误:
Fatal error: Class 'FooClass' not found in /Users/myusername/phar-creation-and-require-test/testoflibrary.php on line 5
为了达到这种状态,我一直在阅读 the docs 、 this tutorial 和 this tutorial 。 This SO question 似乎没有提供我需要的信息,也没有提供 this question ,而且我似乎无法在 SO 上找到任何其他相关问题/答案。
所以,问题(再次)是,
我如何正确创建然后需要 PHAR 文件?
最佳答案
一次添加一个文件(即使只有一个文件)也会失败。只需一次从包含所有库源文件的整个目录构建 PHAR 文件。
例如使用这样的项目结构:
libraryproject/
src/
subfolder1/
athing.php
anotherthing.php
athing.php
anotherthing.php
phar-index.php (main file that imports the rest of the library)
make-phar.sh
make-phar.php
mylibrary.phar (after creation)
test-the-lib-works.php
make-phar.php
脚本应该是这样的:
<?php
$phar = new Phar('mylibrary.phar');
$phar->buildFromDirectory('src/'); // This does the thing you actually want.
$phar->setDefaultStub('phar-index.php');
然后make-phar.sh
脚本是这样的:
#!/usr/bin/env 庆典
rm mylibrary.phar
php --define phar.readonly=0 ./make-phar.php
关于php - 如何正确创建然后需要 PHAR 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38214154/