Ads

Wednesday, 25 September 2013

How To create or use php - phar archives

I am showing you how to create phar Library. Here is sample code

Create file in "classes/sample1.php"

 <?  
 /**  
  * Phar demo sample Class   
  * Created By Nikunj Kansara  
  */  
 class Sample1 {  
   var $sName;  
   var $sVersion;  
   // constructor  
   function Sample1() {  
     $this->sName = 'I am Nikunj Kansara';  
     $this->sVersion = '1.0.0';  
   }  
   function getAnyContent() {  
     return '<h1>Demo Test For Phar :: getAnyContent</h1>';  
   }  
   function getContent2() {  
     return '<h2>Demo Test For Phar :: getAnyContent2</h2>';  
   }  
 }  
 ?>  

Create another file in "classes/sample2.php"

 <?  
 /**  
  * Phar demo sample Class   
  * Created By Nikunj Kansara  
  */  
 class Sample2 extends Sample1 {  
   // constructor  
   function SampleClass2() {  
     $this->sName = 'I am Sample class 2';  
     $this->sVersion = '1.0.2';  
   }  
   function getAnyContent() {  
     return '<h1>Phar Test Sample class 2</h1>';  
   }  
 }  
 ?>  

Create index file in "classes/index.php"

 <?  
 require_once('sample1.php');  
 require_once('sample2.php');  
 ?>  

Now, Create phar.php for execute

 <?  
 /**  
  * Created Demo application for test Phar features  
  * Created By Nikunj Kansara  
  */  
 //phpinfo();  
 ini_set("display_errors","1");  
 $sLibraryPath = '/var/www/demo/phar/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('/var/www/demo/phar/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');  
 // demonstration of work  
 $pharClass1 = new Sample1();  
 echo $pharClass1->getAnyContent();  
 echo '<pre>';  
 print_r($pharClass1);  
 echo '</pre>';  
 $pharClass2 = new Sample2();  
 echo $pharClass2->getAnyContent();  
 echo $pharClass2->getContent2();  
 echo '<pre>';  
 print_r($pharClass2);  
 echo '</pre>';  
 ?>  

No comments:

Post a comment