TwigをPhar化

Twigを使うことが多いですよね。そしてもっとデプロイを楽にしたいですよね。
PHPにはpharという(javaでいうjarみたいな)機能があってファイルをまとめることができます。
via: PHP: はじめに - Manual

というわけで、Twigをphar化すれば良いというわけで以下に手順のメモ

compile.phpを作成

まずはtwigをgitから取得

$ git clone https://github.com/fabpot/Twig.git

コンパイラーでtwig.pharを作成

<?php
$phar = new Phar('twig.phar', 0, 'twig.phar');
$phar->buildFromDirectory(__DIR__ . '/Twig.git/lib');
$phar->compressFiles(Phar::GZ);
$phar->setDefaultStub();
$ php compile.php

もし、php.iniでphar.readonly = on になっている場合はエラーが出るのでoffに

あとは、以下のようにphar://で呼び出せばOK

<?php
#require_once __DIR__ . '/Twig.git/lib/Twig/Autoloader.php'; # <= 普通はこっち
require_once 'phar://'. __DIR__ . '/twig.phar/Twig/Autoloader.php'; # <= phar版
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');
$twig = new Twig_Environment($loader, array(
  'cache' => __DIR__ .'/compilation_cache',
));

echo $twig->render('index.html', array('name' => 'brtriver'));

これで、大量にあったPHPファイルはtwig.pharを扱うだけで済むようになります。
便利ですよね。

gist: https://gist.github.com/1653293