Packing Phar

The swoft-cli tool provides a simple command to package a php application (not limited to swowt) into a Phar package.

To use this feature, make sure the phar extension is enabled. Normally, this extension is enabled by default in php.

Build Phar

 php -d phar.readonly=0 swoftcli phar:pack -o=myapp.phar 

Available options ( by help with viewing ):

  • -c, --config specifies the configuration file for packaging. By default, it reads phar.build.inc current directory.
  • --dir The application directory to be packaged. The default is the current directory.
  • -o, --output name of the file to be app.phar after packaging. The default is app.phar

Note: The runtime must be preceded by the option php -d phar.readonly=0

running result:

Pack-phar

Phar package configuration

Phar packaging requires a configuration file to configure some directories, files, etc. that need to be packaged. Usually placed in the project root directory.

 <?php
/**
 * The is a config file for compile phar package.
 * @var \Swoft\Console\Advanced\PharCompiler $compiler
 */

// config
$compiler
    // 删除代码注释。打包swoft 应用需要配合 setStripFilter()
    ->stripComments(true)
    ->setShebang(true)
    // 需要打包的文件后缀,内置已经包含了 .php
    ->addSuffix(['.tpl', '.json'])
    // 排除打包目录,排除一些无用的目录,可以有效减少输出文件大小
    ->addExcludeDir([
        'test',
        'doc',
        'docs',
        'tests',
        'Tests',
        'example',
        'runtime',
        'swoole-ide-helper',
    ])
    // 指定添加的文件
    ->addFile([
        'LICENSE',
        'composer.json',
        'README.md',
        'bin/bootstrap.php',
    ])
    ->setCliIndex('bin/swoft') // 应用入口
    // ->setWebIndex('web/index.php')
    // ->setVersionFile('config/config.php')
;

// 那些目录需要去除注释。Swoft 相关都不能去除注释
$stripDirs = [
    'psr/',
    'nikic/',
    'monolog/',
    'symfony/',
    'toolkit/',
];

$compiler->setStripFilter(function ($file) use ($stripDirs) {
    /** @var \SplFileInfo $file */
    $path = $file->getPathname();

    foreach ($stripDirs as $dir) {
        if (\strpos($path, $dir)) {
            return true;
        }
    }

    return false;
}); 

Expand Phar package

Expand a packaged phar, similar to decompression.

 swoftcli phar:unpack myapp.phar 
/docs/2.x/en/tool/swoftcli/build-phar.html
progress-bar