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

Asked

Viewed 1,077 times

10

Someone has information about the function phar?

What is, what is it for, how to use and what is the advantage?

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

1 answer

7


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 jar (Java Archive) already known to people who work with Java.

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

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

Below I separated some code snippets from the Compiler Composer who use the 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 may have more information about the Phar in PHP documentation (in English):

Browser other questions tagged

You are not signed in. Login or sign up in order to post.