Apelog

Smarty互換でSmartyより軽量なTemplateLiteを使う
に書いた後適度に使っていたところ、Smartyと決定的な差異を発見。

TemplateLiteはオブジェクトにアクセスできない。はじめからオブジェクトをアサインしないような作りにしておけば問題無いものの、既にSmartyでオブジェクトをアサインして使っている場合、テンプレートエンジンをそのまま差し替えるわけにはいかないので注意。

例えば、Zend_Validateのエラー結果を纏めて以下のようなクラスに渡したオブジェクトをアサインしているとする。

<?php
/**
 * @package Sample
 */
class Sample_Validate_Result {
    /**
     * @var array
     */
    private $_errors;

    /**
     * @param array $errors
     */
    public function __construct(array $errors) {
        $this->_errors = $errors;
    }

    /**
     * エラーの有無を返す
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name) {
        if (array_search($name, $this->_errors) !== false) {
            return true;
        } elseif (!array_key_exists($name, $this->_errors)) {
            return false;
        } else {
            return new Sample_Validate_Result($this->_errors[$name]);
        }
    }
}

その状態でテンプレートからアサインしたオブジェクトのメンバ変数にアクセスしようとTemplateLiteの場合、evalに失敗してエラー。

<?php
// Validatorから帰ってくるエラー例
$errorArray = array(
    'nickname'    => array('isEmpty'),
    'mailaddress' => array('tooLong', 'invalid')
);

// コントローラー内でエラーオブジェクトをアサイン
$this->view->errors = new Sample_Validate_Result($errorsArray);

// Smartyならこれができる
{ if $errors->nickname->isEmpty }

完全互換だと思っていて差し替えが後になってしまうと、影響範囲も広がってしまうので記憶の片隅にでも。

SmartyはPHPのテンプレートエンジンでは最も有名で利用者も多いが重い。

TemplateLiteはLGPLライセンスのSmarty互換テンプレートエンジンでSmartyより早いとのこと。PHP5.1.1でSmartyとのベンチマーク比較を見る限りテンプレートで色々やってると結構差が出そう。

公式に書かれている、「TemplateLiteを使うべき7つの理由(意訳)」

  1. Smartyよりコンパイルが早い
  2. Smartyより表示が速い
  3. Smartyと比較してメモリ使用量が少ない
  4. Smartyの機能のほとんどをサポート
  5. Smartyの代替となる
  6. 各リリースに合わせて機能追加される
  7. 活発な開発プロジェクト

6.の「各リリース」というのはSmartyに合わせてという事かな。気になるなら原文参照。

使い方もSmartyと同じなのでSmartyの重さが気になっているなら丁度良い代替になりそう。ZendFrameworkのViewとして使う場合も、Smartyの部分をTemplateLiteに置き換えればそのまま動作する。

単純なページだとそこまで差が出ないので、純粋にincludeのコストが気になる場合はSimplateなどの PHP Extention なテンプレートエンジンを使った方が良い。

以下ZendFrameworkのViewRenderer用クラス。ZendFrameworkの別テンプレートエンジン使用方法はZend FrameworkのViewをSmartyに変更するにはを参照。

<?php
require_once 'Zend/View/Interface.php';
require_once 'class.template.php';

class Sample_View_TemplateLite implements Zend_View_Interface
{
    /**
     * TemplateLite object
     * @var Template_Lite
     */
    protected $_templateLite;

    /**
     * コンストラクタ
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
        $this->_templateLite = new Template_Lite;

        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->_templateLite->$key = $value;
        }
    }

    /**
     * テンプレートエンジンオブジェクトを返します
     *
     * @return Template_Lite
     */
    public function getEngine()
    {
        return $this->_templateLite;
    }

    /**
     * テンプレートへのパスを設定します
     *
     * @param string $path パスとして設定するディレクトリ
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_templateLite->template_dir = $path;
            return;
        }

        throw new Exception('無効なパスが指定されました');
    }

    /**
     * 現在のテンプレートディレクトリを取得します
     *
     * @return string
     */
    public function getScriptPaths()
    {
        return $this->_templateLite->template_dir;
    }

    /**
     * setScriptPath へのエイリアス
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * setScriptPath へのエイリアス
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * 変数をテンプレートに代入します
     *
     * @param string $key 変数名
     * @param mixed $val 変数の値
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_templateLite->assign($key, $val);
    }

    /**
     * 代入された変数を取得します
     *
     * @param string $key 変数名
     * @return mixed 変数の値
     */
    public function __get($key)
    {
        return $this->_templateLite->get_template_vars($key);
    }

    /**
     * empty() や isset() のテストが動作するようにします
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_templateLite->get_template_vars($key));
    }

    /**
     * オブジェクトのプロパティに対して unset() が動作するようにします
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_templateLite->clear_assign($key);
    }

    /**
     * 変数をテンプレートに代入します
     *
     * 指定したキーを指定した値に設定します。あるいは、
     * キー => 値 形式の配列で一括設定します
     *
     * @see __set()
     * @param string|array $spec 使用する代入方式 (キー、あるいは キー => 値 の配列)
     * @param mixed $value (オプション) 名前を指定して代入する場合は、ここで値を指定します
     * @return void
     */
    public function assign($spec, $value = null)
    {
        if (is_array($spec)) {
            $this->_templateLite->assign($spec);
            return;
        }

        $this->_templateLite->assign($spec, $value);
    }

    /**
     * 代入済みのすべての変数を削除します
     *
     * Zend_View に {@link assign()} やプロパティ
     * ({@link __get()}/{@link __set()}) で代入された変数をすべて削除します
     *
     * @return void
     */
    public function clearVars()
    {
        $this->_templateLite->clear_all_assign();
    }

    /**
     * テンプレートを処理し、結果を出力します
     *
     * @param string $name 処理するテンプレート
     * @return string 出力結果
     */
    public function render($name)
    {
        return $this->_templateLite->fetch($name);
    }
}

そのまんまですが。

標準のZend Viewより使い慣れたSmartyを使いたかったので差し替えてみることに。

Zend Framework: Document - 35.3.2. 別のテンプレートシステムの使用の項目だけだとSmartyは呼び出せても実際どうやってControllerに組み込むの?となってしまう。

とりあえずControllerのViewを差し替えてみるかと思いZend_Controller_Actionを継承してinit()でSmartyを差し替えた。

<?php
class Sample_Controller_Action extends Zend_Controller_Action {
    /**
     * @var Zend_Config
     */
    protected $_config;

    public function init() {
        // コンフィグの読み込み
        $this->_config = Zend_Registry::get('config');

        $extraParams = array(
            'compile_dir' => $config->smarty->compile_dir,
        );
        $this->view = new Sample_View_Smarty(null, $extraParams);
        $this->viewSuffix = 'tpl';
    }
}

が、上記だと上手くいかなかったわけで。

続いてActionHelperのViewRendererとしてSmartyを登録する方法で挑戦。

 $config->smarty->compile_dir,
);

// マニュアルに書かれているSmarty用View
$view = new Sample_View_Smarty(null, $extraParams);

$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view);
$viewRenderer->setViewBasePathSpec($config->smarty->template_dir)
    ->setViewScriptPathSpec(':controller/:action.:suffix')
    ->setViewScriptPathNoControllerSpec(':action.:suffix')
    ->setViewSuffix('tpl');

Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

上記方法で変更出来た。

これは継承したinit()では書かず、Controllerが呼ばれる前に書いた(Zend_Controller_Front::run()の前)。複数のテンプレートエンジン使い分ける事はほとんど無いと思われるのでこれで大丈夫かなと。