What is and how does PHP's PHAR function work?

10

Does anyone have information about the phar function?

What is it, what is it for, how is it used and what is the advantage?

I found a lot on the internet, but nothing so specific, so I decided to ask.

    
asked by anonymous 10.04.2017 / 01:22

1 answer

6

The class Phar is used to package PHP applications into a single file that can be easily distributed and executed. This name comes from PHP Archive and was inspired by the already known jar (Java Archive) files with those who work with Java.

It can also be used to manipulate compressed files in zip or tar from class PharData , abstracting their methods in a similar way that PDO does with databases.

A very common case of using Phar is Composer , a tool used for package management in PHP. In your source code we have a class called Compiler that uses Phar to generate the package that is distributed via download to users.

Below I have separated some code snippets from Compiler of Composer using Phar

// Cria um novo arquivo phar
$phar = new \Phar($pharFile, 0, 'composer.phar');

// Abre o resource para receber os arquivos
$phar->startBuffering();

// O Compiler tem esse método addFile, que passa um arquivo e a
// classe Phar
$this->addFile($phar, $file);

// Dentro do addFile, ele tem algumas funções para minificar o código do
// Composer, tirando espaços em branco do $file
// Em seguinda, depois de limpar o arquivo, ele executa um método do phar
// que cria um arquivo no mesmo path minificado
$phar->addFromString($path, $content);

// Esse setStub seria o script que executa sua aplicação, o runner principal
$phar->setStub($this->getStub());

// E pra fechar o arquivo, chamamos o método abaixo
$phar->stopBuffering();

We can have more information about Phar in the PHP documentation:

10.04.2017 / 01:55