非常に単純な Hello World の仕組みをまとめてみました。ブラウザからアクセスされる .php ファイルに Smarty が include(require) され、指定したテンプレートに変数の値が埋め込まれて表示される、一連の流れです。まとめずらく、若干見づらいですね。
Smarty のインストール
PHP の勉強を始めると、ひとつのファイルの中に html と php の記述がごっちゃり入って、わけがわからなくなってきます。もっとスマートにスマートにファイルを分けられないものかと思っていたら、あるんですね、テンプレートエンジンというものが。
調べると、楽天やサイボウズでも使われているようでおどろきです。
公式サイト・ドキュメントなど
ダウンロードは Smarty : Download から、日本語のドキュメントは Smarty – コンパイリング PHP テンプレートエンジン で確認することができるようです。
検証環境
環境はいつものとおり。ほんとにやってみて、動いたというレベルなので参考にはしないでください。
- CentOS 5.3
- Apache2.2
- php5.1.6
Smarty のインストール
まずは、wget でダウンロードして解凍します。
[root@centos ~]# wget http://www.smarty.net/do_download.php?download_file=Smarty-2.6.25.tar.gz [root@centos ~]# tar xvzf Smarty-2.6.25.tar.gz
解凍してできたフォルダをリネームします。
[root@centos ~]# mv Smarty-2.6.25 Smarty
Smarty 本体を格納するディレクトリを作成し、Smarty を移動します。
[root@centos ~]# mkdir /usr/local/lib/php [root@centos ~]# mv Smarty /usr/local/lib/php/
Smarty 用のディレクトリの準備
Smarty で使用するテンプレートや、コンパイルされた PHP ファイルが格納されるディレクトリを作成します。これらのディレクトリはサーバ単位ではなく、コンテンツ単位で必要になるようです。*1
[root@centos ~]# mkdir -p /var/www/html/smarty [root@centos ~]# cd /var/www/html/smarty [root@centos ~]# mkdir templates templates_c configs cache
各フォルダやディレクトリに apache が書き込みや変更ができるようにパーミッションの変更を行います。
[root@centos ~]# chown -R apache:apache /var/www/html/smarty [root@centos ~]# chmod 777 /var/www/html/smarty/templates_c [root@centos ~]# chmod 777 /var/www/html/smarty/cache
php.ini を編集します。以下の編集を行うと、Smarty のライブラリファイルを呼び出す際に、フルパスではなく「require_once ‘Smarty.class.php’;」だけ書けばよいので簡潔になります。フルパスで指定してもいいけどね。php.ini を編集したら、httpd の再起動をしておきます。
[root@centos ~]# vi /etc/php.ini (色々省略) ;;;;;;;;;;;;;;;;;;;;;;;;; ; Paths and Directories ; ;;;;;;;;;;;;;;;;;;;;;;;;; ; UNIX: "/path1:/path2" ;include_path = ".:/php/includes" include_path = ".:/usr/share/pear:/usr/local/lib/php/Smarty/libs" [root@centos ~]# service httpd restart
動作確認
サンプルの php ファイルを用意します。
[root@centos ~]# vi /var/www/html/index.php
<?php
require ('Smarty.class.php');
$smarty = new smarty();
$smarty->template_dir = '/var/www/html/smarty/templates';
$smarty->compile_dir = '/var/www/html/smarty/templates_c';
$smarty->cache_dir = '/var/www/html/smarty/cache';
$smarty->config_dir = '/var/www/html/smarty/configs';
$smarty->assign('name', '太郎');
$smarty->display('index.tpl');
?>
サンプルのテンプレートを用意します。
[root@centos ~]# vi /var/www/html/smarty/templates/index.tpl
<html>
<head>
<title>Smarty</title>
</head>
<body>
Hello, {$name}!
</body>
</html>
ブラウザから、index.php にアクセスすると
とりあえず動いた。けど、まだよくわからないな?
*1 @IT : Smartyでテンプレートエンジンの威力を知る 「Smartyを動作させるには、PHPスクリプトとテンプレート以外に、4つのディレクトリ(tempalates/templates_c/configs/cache)を必要とします。これらのディレクトリはサーバ単位ではなく、コンテンツ単位で用意することが推奨されています。」
参考にしたサイト







