Generating a PHAR for a simple application

前端 未结 1 1643
别那么骄傲
别那么骄傲 2021-01-30 01:46

I\'m experimenting in building CLI tools using the Symfony2 console library. I\'ve got something basic working and now I want to package it as a phar. I\'ve read a few examples

相关标签:
1条回答
  • 2021-01-30 02:34

    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 63
    foreach ($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.

    0 讨论(0)
提交回复
热议问题