【问题标题】:How do I correctly create, and then require a PHAR file?如何正确创建,然后需要 PHAR 文件?
【发布时间】: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 docsthis tutorialthis tutorialThis SO question 似乎没有提供我需要的信息,this question 也没有提供,我似乎在 SO 上找不到任何其他相关问题/答案。

所以,问题(再次)是,

如何正确创建然后需要 PHAR 文件?

【问题讨论】:

  • 首先确保您的 phar 有效。 php -l mylibrary.phar 应该进行语法检查,就像任何其他 PHP 文件一样。你试过简单的require "mylibrary.phar";吗?
  • 语法检查没有错误,require "mylibrary.phar"; 也不起作用。它就在测试脚本旁边,所以... ⎺\_(ツ)_/⎺

标签: php phar


【解决方案1】:

一次添加一个文件(即使只有一个文件)将失败。只需从包含库的所有源文件的整个目录构建 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 bash

rm mylibrary.phar
php --define phar.readonly=0 ./make-phar.php

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 2014-12-27
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多