Generating a PHAR for a simple application Generating a PHAR for a simple application php php

Generating a PHAR for a simple application


I suggest you to take a look at Composer's Compiler (it's originally created by Fabien Potencier in Silex). In that class, you can see how a big console application like Composer creates the .phar file.


Some interesting parts:

// line 49$phar = new \Phar($pharFile, 0, 'composer.phar');$phar->setSignatureAlgorithm(\Phar::SHA1);$phar->startBuffering();

Phar#startBuffering starts the creation of the phar file.

// Line 54$finder = new Finder();$finder->files()    ->ignoreVCS(true)    ->name('*.php')    ->notName('Compiler.php')    ->notName('ClassLoader.php')    ->in(__DIR__.'/..')

Here, Composer uses the Symfony2 Finder Component to find every file in the src directory (except this file and the autoloader).

// Line 63foreach ($finder as $file) {    $this->addFile($phar, $file);}

Here, Composer iterates over every found file and adds it to the Phar archive. (you can see the Compiler#addFile method on line 116).

This is repeated some times. And then at line 93, the Composer autoloader is used:

$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/autoload.php'));$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_namespaces.php'));$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_classmap.php'));$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../vendor/composer/autoload_real.php'));

Because Phar is a stream, the directory structure is kept in the phar file and the Composer autoloader is still able to load the classes.

Then, at the end, the stubs are added and the buffering stopped:

$phar->setStub($this->getStub());$phar->stopBuffering();

(see the Compiler#getStub method at line 173). The Phar#stopBuffering method stops the creation of the phar and saves it to the phar file.

To make this story complete, Composer creates a very simple CLI compile file which runs this command.