The New .phar PHP Package
Today I discovered a very powerful addition to the PHP world. Phar is an archive extension for PHP that allows an entire PHP application to be packaged into a single file. It’s basically PHP’s answer to Java’s .jar archive format. Don’t get excited yet, it gets better . . .
There are a few things that make this particularly handy. For one, it is being integrated into the next major PHP release (5.3) wich means that any standard PHP installation running the latest version will support .phar files right out of the box.
The other advantage is of course in deployment. Using a .phar file you can deploy an entire PHP application by working with just one file, rather than a buch of files and directories. This is where .phar really shines. Imagine deploying a popular web app like WordPress by simply copying a single .phar file to your web server’s root, rather than figuring out how to zip it up, upload it, and somehow unzip it remotely. Piece of cake!
The devlopment side is equally as simple, being able to access files within the .phar file as easily as if it were another directory in the filesystem. The .phar file itself can be included in a script using any of PHP’s standard import constructs (include, include_once, require, require_once). This also means external libraries can be more easily integrated, having just a single file to include in order to utilize a given library. A .phar archive can also be accessed as a stream using the same functions used to read/write other types of streams.
// Referencing a .phar archive or its contents: include 'userlibrary.phar'; include 'phar://userlibrary.phar/internal/file.php'; // Utilizing the Phar Stream Wrapper: header('Content-type: image/jpeg'); echo file_get_contents('phar://userlibrary.phar/img/image.jpg');
Certainly there are disadvantages as well, and this is not a one-size-fits-all solution. Using .phar files does result in a performance hit, meaning traffic-intensive sites and heavyweight applications are probably not the best place to use this tool. It also may not be ideal for a web app that is fairly modular, or other situations where source files might be added or removed on a regular basis. It does have its uses though, and for me it will be a welcome addition to the PHP core.