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

标签 php phar

我目前正在尝试打包库代码,然后将其发送给实际尝试使用该库代码的人。创建 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 文件。

例如使用这样的项目结构:

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/

相关文章:

nginx - 包含多个 phar 文件时出现 Php5-FPM 错误

php - PHAR createDefaultStub 是否应该区分 CLI 和浏览器?

php - Elasticsearch:如何在聚合中使用多重过滤和计算?

php - 它没有为我的查询结果输出任何行,这是为什么?

php - 在 codeigniter 中多次返回相同的结果

php - PharData extractTo 方法在 linux 环境下提取 .tar.gz 失败

php - 使用 PHP 将图像上传到数据库 (MySql)

javascript - 如何获取 data-id 的值并将其放入 twitter Bootstrap 模式中?

php - 使用 php PharData 提取带有空目录的 tar 存档

php - 如何在 Ubuntu 上安装 Phar?