How to create and then require a PHAR file?

I'm currently trying to pack library code, which will then be sent to people who are really trying to use this library code. After creating the PHAR file, I try to verify that this was done with a simple script test. At some point in the create-PHAR → use-PHAR process, I am doing something wrong.

How to create and then require a PHAR file?

To simplify the creation and validation of PHAR, I limited everything to a simplified version of the problem and cannot continue.

Here are my files:

~/phar-creation-and-require-test/ mylibrary.php testoflibrary.php make-phar.php make-phar.sh mylibrary.phar (after being created) 

mylibrary.php Contents:

 <? class FooClass { private $foonum; function FooClass() { $this->foonum = 42; } } ?> 

make-phar.php Contents:

 <?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'); 

which is called make-phar.sh :

 #!/usr/bin/env bash rm mylibrary.phar php --define phar.readonly=0 ./make-phar.php mylibrary.phar \ phar-index.php 

I can run make-phar.sh without any errors and mylibrary.phar is created.

So the test script 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); 

When I run it with php testoflibrary.php , I get this error:

 Fatal error: Class 'FooClass' not found in /Users/myusername/phar-creation-and-require-test/testoflibrary.php on line 5 

To get to this state, I read the documents , this textbook , as well as this textbook . This SO question doesn't seem to give me the information I need, but this question , and I can't seem to find other relevant questions / answers here on SO.

So, the question (again) is,

How to create and then require a PHAR file?

+5
source share
1 answer

Adding files one at a time (even with one file) will fail. Just create a PHAR file from the entire directory containing all the library source files at once.

eg. With your project structure like this:

 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 script should look like this:

 <?php $phar = new Phar('mylibrary.phar'); $phar->buildFromDirectory('src/'); // This does the thing you actually want. $phar->setDefaultStub('phar-index.php'); 

Then make-phar.sh script: #! / Usr / bin / env bash

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

All Articles