PHPでWebアプリケーションを開発していると、HTMLとPHPコードが混在して管理しづらくなることがあります。
そんな問題を解決するのが Smarty です。
Smartyは、HTML(表示)とPHP(処理)を分離するためのテンプレートエンジンです。
本記事では、Smarty公式サイトのQuick Installをもとに、インストールからHello World表示までを分かりやすく解説します。
Smartyとは?

Smartyを利用すると、PHPコードをHTML内に直接書く代わりに、テンプレート記法で変数を表示できます。
<?php
echo $user_name;
?>Smartyでは次のように書けます。
{$user_name}これにより、以下のようなメリットがあります。
- デザイナーはHTMLだけ編集しやすい
- プログラマーはPHP処理に集中しやすい
- 表示と処理を分離できる
- 保守性が向上する
インストール方法
現在はComposerでの導入が最も簡単です。
composer require smarty/smartyこれだけでSmartyがインストールされます。
Composerを使わない場合
Smarty公式サイトからダウンロードして配置します。
例:
cd YOUR_DOWNLOAD_DIR
tar -zxvf Smarty-*.*.tar.gz
mkdir /usr/local/lib/php/Smarty
cp -r Smarty-*.*/libs/* /usr/local/lib/php/Smartyインストール後の構成例です。
/usr/local/lib/php/Smarty/
├── Smarty.class.php
├── debug.tpl
├── plugins/
└── sysplugins/Smartyに必要なディレクトリ
Smartyは最低でも以下の4つのディレクトリを使用します。
project/
├── templates/
├── templates_c/
├── cache/
└── configs/| ディレクトリ | 用途 |
|---|---|
| templates | テンプレートファイル .tpl |
| templates_c | コンパイル済みテンプレート |
| cache | キャッシュファイル |
| configs | 設定ファイル |
templates_c と cache はSmartyが書き込みを行うため、Webサーバーユーザーに書き込み権限が必要です。
Linuxでディレクトリ作成
mkdir templates
mkdir templates_c
mkdir cache
mkdir configs権限設定
Smartyは以下のディレクトリへ書き込みを行います。
templates_c
cacheそのため、Webサーバーユーザーに書き込み権限が必要です。
例:
chmod 770 templates_c
chmod 770 cacheCentOS系でApacheを利用している場合は、以下のように所有者を変更する方法もあります。
chown apache:apache templates_c
chown apache:apache cacheHello Worldを表示してみる
テンプレート作成
templates/index.tpl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Smarty Sample</title>
</head>
<body>
<h1>Hello {$name}!</h1>
</body>
</html>PHPファイル作成
index.php
<?php
require 'vendor/autoload.php';
use Smarty\Smarty;
$smarty = new Smarty();
$smarty->setTemplateDir(__DIR__ . '/templates/');
$smarty->setCompileDir(__DIR__ . '/templates_c/');
$smarty->setCacheDir(__DIR__ . '/cache/');
$smarty->setConfigDir(__DIR__ . '/configs/');
$smarty->assign('name', 'WEBENG');
$smarty->display('index.tpl');ブラウザでアクセスすると、以下のように表示されます。
Hello WEBENG!変数を渡す
PHP側で assign() を使うと、テンプレートへ値を渡せます。
PHP
$smarty->assign('title', '会員一覧');
$smarty->assign('user_name', '山田太郎');Smarty
<h1>{$title}</h1>
<p>{$user_name}</p>出力
<h1>会員一覧</h1>
<p>山田太郎</p>配列を渡す
PHP
$users = [
'田中',
'佐藤',
'鈴木'
];
$smarty->assign('users', $users);Smarty
<ul>
{foreach $users as $user}
<li>{$user}</li>
{/foreach}
</ul>出力
<ul>
<li>田中</li>
<li>佐藤</li>
<li>鈴木</li>
</ul>条件分岐
PHP
$smarty->assign('login', true);Smarty
{if $login}
ログイン中
{else}
未ログイン
{/if}出力
ログイン中HTMLエスケープ
XSS対策として、画面に出力する値はエスケープするのが基本です。
個別にエスケープする場合は、次のように書きます。
{$name|escape}自動エスケープを有効にする場合は、PHP側で次のように設定します。
$smarty->setEscapeHtml(true);よくあるエラー
templates_c に書き込めない
エラー例:
unable to write file原因:
templates_c
cacheに書き込み権限がありません。
対策:
chmod 770 templates_c cacheまたは、Webサーバーユーザーに所有者を変更します。
chown apache:apache templates_c cacheテンプレートが見つからない
エラー例:
Unable to load template原因:
$smarty->setTemplateDir()のパスが間違っている可能性があります。
対策:
$smarty->setTemplateDir(__DIR__ . '/templates/');のように、絶対パスに近い形で指定すると安全です。
Smarty.class.php が見つからない
エラー例:
Failed opening required Smarty.class.php原因:
requireのパス設定ミスです。
Composerを使っている場合は、以下を読み込みます。
require 'vendor/autoload.php';手動インストールの場合は、Smartyを配置したパスに合わせて指定します。
require '/usr/local/lib/php/Smarty/Smarty.class.php';実践的なディレクトリ構成例
project/
├── public/
│ └── index.php
│
├── templates/
│ └── index.tpl
│
├── templates_c/
│
├── cache/
│
├── configs/
│
└── vendor/public/ をWeb公開ディレクトリにし、templates/ や templates_c/ は公開領域の外に置く構成がおすすめです。
まとめ
SmartyはPHPの表示層とロジック層を分離するための定番テンプレートエンジンです。
導入手順は次の4ステップです。
- Smartyをインストールする
templates/templates_c/cache/configsを作成する- Smartyオブジェクトを生成する
assign()で値を渡し、display()で表示する
最初は「Hello World」だけでも動かしてみると、Smartyの仕組みがよく理解できます。
新規プロジェクトでは、Composerを使って以下のコマンドから始めるのがおすすめです。
composer require smarty/smartySmartyを使うことで、PHPアプリケーションのテンプレート管理が格段に楽になります。
