
前回はSmartyの基本的な利用方法としてSmartyクラスを初期化して実行しましたが、
Smartyクラスを継承した子クラスを自分で定義して利用する事が出来ます。
テンプレートのパスやエスケープ処理など、Smartyのプロパティ設定を子クラスにあらかじめ定義しておくことでSmartyを利用する際にそれらの設定を毎回行う必要がなくなり便利です。
環境:Smarty 3.1、PHP 7.4.4
Smartyの子クラスを定義する
src/SmartyChild.php
<?php
class SmartyChild extends Smarty
{
public function __construct()
{
parent::__construct();
$this -> template_dir = __DIR__ . '/../templates';
$this -> compile_dir = __DIR__ . '/../templates_c';
$this -> escape_html = true;
}
}
コンストラクタ内で、継承したSmartyクラスのプロパティを上書きするように記述している。
(初期化時に設定される)
実行ファイルからSmartyの子クラスを利用する
index.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/src/SmartyChild.php';
$smarty = new SmartyChild();
$smarty->assign('title', 'Smarty Lesson!');
$smarty->assign('class', 'red');
$smarty->assign('name', 'Taro');
$smarty->display('index.tpl');
