php 5.3新特性的phar

在PHP 5.3中,引入了类似JAVA的JAR之类的打包文件机制.Phar 归档的概念来自 Java™ 技术的 JAR 归档,它允许使用单个文件打包应用程序,这个文件中包含运行应用程序所需的所有东西。该文件不同于单个可执行文件,后者通常由编程语言生成,比如 C,因为该文件实际上是一个归档文件而非编译过的应用程序。因此 JAR 文件实际上包含组成应用程序的文件,但是考虑到安全性,不对这些文件进行仔细区分。Phar 扩展正是基于类似的理念,但是在设计时主要针对 PHP 的 Web 环境。同样,与 JAR 归档不同的是,Phar 归档可由 PHP 本身处理,因此不需要使用额外的工具来创建或使用。

Phar 扩展对 PHP 来说并不是一个新鲜的概念。它最初使用 PHP 编写并被命名为 PHP_Archive,然后在 2005 年被添加到 PEAR 库。然而在实际中,解决这一问题的纯 PHP 解决方案非常缓慢,因此 2007 年重新编写为纯 C 语言扩展,同时添加了使用 SPL 的 ArrayAccess 对象遍历 Phar 归档的支持。自那时起,人们做了大量工作来改善 Phar 归档的性能。


下面例子讲解下:
首先是classes目录下的Samplecalss.php:
<?

class SampleClass {

var $sName;
var $sVersion;

// constructor
function SampleClass() {
$this->sName = 'I am Sample class';
$this->sVersion = '1.0.0';
}

function getAnyContent() {
return '<h1>Hello World from Sample class</h1>';
}

function getContent2() {
return '<h2>Get content 2</h2>';
}

}

?>
另外一个:
<?

class SampleClass2 extends SampleClass {

// constructor
function SampleClass2() {
$this->sName = 'I am Sample class 2';
$this->sVersion = '1.0.2';
}

function getAnyContent() {
return '<h1>Hello World from Sample class 2</h1>';
}

}

?>
再搞一个INDEX.PHP
<?

require_once('SampleClass.php');
require_once('SampleClass2.php');

?>
现在,是想把class目录下的这些文件都打成phar的格式,我们得建立一个lib目录
,主文件
<?

$sLibraryPath = 'lib/SampleLibrary.phar';

// we will build library in case if it not exist
if (! file_exists($sLibraryPath)) {
ini_set("phar.readonly", 0); // Could be done in php.ini

$oPhar = new Phar($sLibraryPath); // creating new Phar
$oPhar->setDefaultStub('index.php', 'classes/index.php'); // pointing main file which require all classes
$oPhar->buildFromDirectory('classes/'); // creating our library using whole directory

$oPhar->compress(Phar::GZ); // plus - compressing it into gzip
}

// when library already compiled - we will using it
require_once('phar://'.$sLibraryPath.'.gz');

$oClass1 = new SampleClass();
echo $oClass1->getAnyContent();
echo '<pre>';
print_r($oClass1);
echo '</pre>';

$oClass2 = new SampleClass2();
echo $oClass2->getAnyContent();
echo $oClass2->getContent2();
echo '<pre>';
print_r($oClass2);
echo '</pre>';

?>

输出如下;
Hello World from Sample class
SampleClass Object
(
[sName] => I am Sample class
[sVersion] => 1.0.0
)

Hello World from Sample class 2
Get content 2
SampleClass2 Object
(
[sName] => I am Sample class 2
[sVersion] => 1.0.2
)

由于要创建自己的打包phar,因此phar.readonly要设置为0,
使用的时候,可以用:
phar://来进行引用

两个很好的phar介绍学习资料:
http://www.ibm.com/developerworks/cn/opensource/os-php-5.3new4/

http://www.slideboom.com/presentations/26182/PHP-5.3-Part-3---Introducing-PHAR
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值