บทนำ
Stream wrapper phar:// พร้อมใช้งานใน PHP ทุกเวอร์ชันหลัง 5.3.0 Phar ย่อมาจาก PHP Archive ใช้สำหรับกระจายแอปพลิเคชันหรือไลบรารี PHP และรันได้เหมือนไฟล์ PHP ธรรมดา phar:// wrapper รองรับการเปิดไฟล์ด้วย fopen() สำหรับอ่าน/เขียน, เปลี่ยนชื่อ, และการดำเนินการกับ directory stream opendir() รวมถึงสร้างและลบไดเรกทอรี
คลาส Phar อนุญาตให้แพ็กเกจทรัพยากรแอปพลิเคชันที่อยู่ในไดเรกทอรีไว้ใน phar archive สำหรับการดำเนินการอ่าน ให้วาง archive นี้ใน phar:// wrapper
สร้าง phar archive
เริ่มต้นด้วยการตรวจสอบให้แน่ใจว่าการตั้งค่า phar.readonly ใน php.ini ตั้งเป็น 0 จากนั้นสร้างโฟลเดอร์ src ที่เก็บทรัพยากรทั้งหมดของแอปพลิเคชัน สร้างไฟล์ index.php
<?php echo "phar application started"; ?>
ใช้ object ของคลาส Phar สร้าง phar archive ที่มีไฟล์ในโฟลเดอร์ src ด้วยเมธอด buildFromDirectory() ระบุ index.php เป็น setDefaultStub
<?php // The php.ini setting phar.readonly must be set to 0 $pharFile = 'app.phar'; // clean up if (file_exists($pharFile)) { unlink($pharFile); } if (file_exists($pharFile . '.gz')) { unlink($pharFile . '.gz'); } // create phar $p = new Phar($pharFile); // creating our library using whole directory $p->buildFromDirectory('src/'); // pointing main file which requires all classes $p->setDefaultStub('index.php', '/index.php'); // plus - compressing it into gzip $p->compress(Phar::GZ); echo "$pharFile successfully created"; ?>รันสคริปต์ข้างต้นจาก command line
php create-phar.php
จะสร้าง app.phar ใน working directory เพื่อรัน phar archive ใช้คำสั่ง
php app.phar
ใช้ phar:// wrapper
<?php echo file_get_contents('phar://app.phar/index.php'); ?>จะแสดงเนื้อหาของไฟล์ index.php