PHP Compression and archive-phar

Source: Internet
Author: User
Tags spl
The Phar archive concept comes from the Java technology JAR Archive, which allows you to package your application with a single file that contains everything you need to run your application. This file differs from a single executable file, which is typically generated by a programming language, such as C, because the file is actually an archive file rather than a compiled application. So the JAR file actually contains the files that make up the application, but with security in mind, these files are not carefully differentiated. The Phar extension is based on a similar concept, but is designed primarily for PHP's WEB environment. Similarly, unlike JAR Archives, Phar archives can be processed by PHP itself, so there is no need to use additional tools to create or use them.

The Phar extension is not a fresh concept for PHP. It was originally written in PHP and named Php_archive, and was added to the PEAR Library in 2005. In practice, however, the pure PHP solution to this problem was very slow, so the 2007 was rewritten as a pure C language extension, with the addition of support for Arrayaccess objects that use SPL to traverse the Phar archive. Since then, a lot of work has been done to improve the performance of Phar archiving.

Create Phar

There are several steps you need to take to create a Phar file. All steps need to be created with some form of PHP command, because there is no standalone tool for creating an archive. In addition, to create and modify the Phar file, the php.ini setting phar.readonly must be set to 0. You do not need to use this setting when opening and referencing files within PHP's Phar archive.

Let's take a look at what steps are required to create a Phar file that can be used to drive an application. The design goal of the application is to load directly from a WEB browser or command prompt. The first step is to create the Phar file, so we'll create the Phar object shown in Listing 1. The object reference will allow you to control all aspects of the Phar archive.

Example 1. Create a Phar object

$p = new Phar ('/path/to/my.phar ', Current_as_fileinfo | Key_as_filename, ' My.phar '); $p->startbuffering ();

the first parameter of a constructor represents the location where the Phar file is saved. The second parameter passes all parameters to the Recursivedirectoryiterator parent class. The third parameter is the alias that references the Phar archive in the context of the stream. So for listing 1, you can use the Phar://my.phar reference file in this Phar archive. You can also issue the phar::startbuffering () method to buffer changes made to the archive until the phar::stopbuffering () command is issued. Although this is not necessarily the case, it does improve the performance of creating or modifying an archive because it avoids the need to save changes made every time the archive is modified in the script.

By default, the Phar created will use the native Phar-based archive format. You can also convert the format to a zip format as shown in Listing 2, using the ZIP or TAR format for the Phar file.
Example 2. Convert storage format to ZIP format

$p = $p->converttoexecutable (phar::zip);


There are pros and cons to converting an archive format. The main advantage is the ability to view archived content using any tool that handles ZIP or TAR files. However, if the Phar archive does not use the native Phar-based archive format, it does not need to load the archive using the Phar extension, which is required in the case of a Phar archive in ZIP or TAR format.

Next, you will need to define a file stub, which is the code that is called first when the Phar file is loaded.

Phar file stub

A file stub is just a small part of the code that was originally run when the Phar file was loaded, and always ends with a __halt_compiler () tag. Listing 3 shows a typical file stub.
Example 3. Phar file stub

<?php    Phar::mapphar ();    Include ' phar://myphar.phar/index.php ';    __halt_compiler ();

The Phar::mapphar () method call shown above performs initialization of the Phar archive by reading the manifest file (manifest). You need to use the phar://flow wrapper to perform initialization before referencing the file within the archive. The initially loaded file will be the first time the application loads, in this case index.php.

How to add this file stub Phar to the Phar archive depends on the format of the archive being used. For Phar-based archiving, using the Phar::setstub () method, it takes the unique parameters of the PHP code and puts it in a stub as a string. Listing 4 illustrates this approach.
Example 4. Creating a file stub with Phar::setstub ()

$p->setstub (' <?php Phar::mapphar (); include ' phar://myphar.phar/index.php '; __halt_compiler ();?> ');

If you plan to use the stub instead of redirecting to the index.php page to complete the operation, you can use the helper method Phar::createdefaultstub () to build the file stub. Therefore, you only need to pass the name of the file that you want to include in the file stub. In Listing 5, rewrite the Phar::setstub () method to use the helper method.

Example 5. Creating a file stub with Phar::createdefaultstub ()

$p->setstub ($p, createdefaultstub (' index.php '));


if the second optional parameter of the Phar,phar::createdefaultstub () method that is loaded from the WEB server is allowed to contain a different file. This is convenient for applications designed for the command line or Web browser context.

For ZIP and TAR-based implementations, store the contents of the above stub in a. phar/stub.php file instead of using the setstub () command.

Adding files to an archive

The Phar object uses the Arrayaccess SPL object to allow access to the archived content as an array, so there are a number of ways to add files to the archive. The simplest approach is to use the Arrayaccess interface directly.
Example 6. Add files to an archive

$p [' file.txt '] = ' This is a text file '; $p [' index.php '] = file_get_contents (' index.php ');

Example 6 indicates that the file name is specified as an array key and the content is specified as a value. You can use the file_get_contents () function to get the contents of an existing file, and then set the content to a value. This gives you more flexibility in adding files to the archive, either by referencing an existing file or by dynamically building the file. The latter method can be used as part of the application build script.

If the files stored in the Phar archive are very large, you can use gzip or bzip2, respectively, through the Pharfileinfo::setcompressedgz () or PHARFILEINFO::SETCOMPRESSEDBZIP2 () method Compress selectively compress files in the archive. In Listing 7, you will use bzip2 to compress the files.
Example 7. Compressing files in an Phar archive using bzip2

$p [' big.txt '] = ' This is a big text file '; $p [' Big.txt ']->setcompressedbzip2 ();

to compress files or use an archive containing compressed files, you must support BZIP2 or zlib (for GZ compressed files) extensions in your PHP installation.

Let's say you need to add a lot of files to the archive. Adding files one at a arrayaccess interface is a very tedious task, so you can use some handy methods. One approach is to use the Phar::buildfromdirectory () method, which iterates through the specified directory and adds the files in it. It also supports filtering of added files by passing the second argument using the file's regular expression pattern to match the file and add it to the archive. Listing 8 shows this process.
Example 8. Use Phar::buildfromdirectory () to add files to an archive

$p->buildfromdirectory ('/path/to/files ', './\.php$/');


Example 8 adds a PHP file from the specified directory to the Phar archive. If you need to make any modifications to the added files, such as compressing the files, you can use the Arrayaccess interface to return.

You can use an iterator (iterator) to add a file through the Phar::buildfromiterator () method. Supports two styles of iterators: one is to map the file name in Phar to the name of the disk file, and the other is to return the Splfileinfo object. Recursivedirectoryiterator is a compatible iterator that shows how to use it to add a catalog file to an archive.
Example 9. Add a catalog file to an archive using Phar::buildfromiterator ()

$p->buildfromiterator (New Recursiveiteratoriterator (New Recursivedirectoryiterator ('/path/to/files ')), '/path/ To/files ');

the Phar::buildfromiterator () method accepts the iterator object itself as a unique parameter. In the example above, you have wrapped the Recursivedirectoryiterator object with the Recursiveiteratoriterator object, and the Recursiveiteratoriterator object provides Phar: The compatible iterator required by the Buildfromiterator () method.

We have now created a Phar archive that can be used with any PHP application. Let's take a look at how this archive is easy to use.

Using Phar archiving

One advantage of Phar archiving is that it can be easily integrated into any application. This is especially true if you are using a native Phar-based archive format. In this case, you don't even need to install the Phar extension, because PHP is inherently able to load files and extract file contents. ZIP and TAR-based archiving requires the Phar extension to be loaded.

Phar archiving is included in the application at design time, just like regular PHP files, which makes it very easy for application developers who are already familiar with how to include other third-party code to use the Phar archive. Let's take a look at how easy it is to integrate Phar in an application.

Integrating Phar Archive code in your application

The easiest way to integrate code in a Phar archive is to include the Phar archive, and then include the files you need to use in the Phar file. The phar://stream wrapper can be used to access files in the loaded Phar Archive, as shown below.
Example 10. Loading code in the Phar archive

Include ' Myphar.phar ';  Include ' phar://myphar.phar/file.php ';

The first include loads the Myphar.phar archive, which contains the code specified in the file stub. The second include opens the Phar archive with a flow wrapper and includes only the specified files in the archive. Note Before you include the file in the archive, you do not need to include the Phar archive itself, as shown in Listing 10.

Running PHP applications from Phar archive

An excellent feature of the Phar archive is the ability to package the entire application and publish it using a single Phar archive. The advantage of this approach is that it simplifies application deployment and does not degrade performance, thanks primarily to the addition of several Phar enhancements in PHP V5.3. However, the following points should be considered when designing an application to run in Phar:

Any application-specific files that need to be created, such as config files, cannot be part of the archive, so they need to be written to a separate but accessible location. If your application creates a cache file that makes up the extension, the same is true for these files.

You should always use the Phar-based archive format and not compress the files in the archive for maximum flexibility. ZIP and TAR-based archiving requires the Phar extension to be installed in PHP, while Phar-based archiving can even be used for situations where Phar extensions are not installed.

Any file references in the application need to be modified to use both the phar://stream wrapper and the archive name, as shown in the previous section.

PHPMyAdmin is a popular PHP application that has been packaged with Phar to demonstrate the simplicity of using PHAR archiving. It has been designed to run from Phar archive files, but it still has the ability to store configuration files outside of Phar archives.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.