【发布时间】:2016-10-04 01:32:52
【问题描述】:
我目前正在尝试打包库代码,然后将其发送给实际尝试使用该库代码的人。创建 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 有效。
php -l mylibrary.phar应该进行语法检查,就像任何其他 PHP 文件一样。你试过简单的require "mylibrary.phar";吗? -
语法检查没有错误,
require "mylibrary.phar";也不起作用。它就在测试脚本旁边,所以... ⎺\_(ツ)_/⎺