研修(Smartyインストールと設定)
テンプレートエンジンである、Smartyを用いる。
■テンプレートエンジン
ロジックの部分(プログラム)とテンプレート(html)部分を分けて作成し、
プログラムとデザインを別々に管理できるソフトウェア。
PHPのためのテンプレートエンジン。
特徴
・高速
・コンパイルが一度のみで済む
・変更されたテンプレートファイルのみ再コンパイルする
1.インストールファイル取得
/usr/local/src上でインストールファイルをダウンロード、展開
# wget http://www.smarty.net/do_download.php?download_file=Smarty-2.6.25.tar.gz # tar zxvf Smarty-2.6.26.tar.gz # ll /usr/local/src/ -rw-r--r-- 1 root root 153034 6月 18 23:57 Smarty-2.6.26.tar.gz -rw-r--r-- 1 root root 153034 6月 18 23:57 Smarty-2.6.26
2.パス・ディレクトリ設定
Smarty-2.6.25を/usr/local/libに移動。
# mv Smarty-2.6.25 /usr/local/lib # vi /usr/local/lib/php.ini ;;;;;;;;;;;;;;;;;;;;;;;;; ; Paths and Directories ; ;;;;;;;;;;;;;;;;;;;;;;;;; ; UNIX: "/path1:/path2" ;include_path = ".:/php/includes" include_path = ".:/php/includes:/usr/local/lib/php/:/usr/local/lib/Smarty-2.6.26/libs" ↑パス追加 # /usr/local/apache2/bin/apachectl restart
Smartyには
・テンプレートを置くディレクトリ
・コンパイル済みのテンプレートを置くディレクトリ
を作成する必要がある。
アクセスできない位置に置いておく。
今回はhtdocsと同じ階層にディレクトリ作成して置く。
# mkdir templates # mkdir templates_c
3.設定ファイル
以下ソース。
// Smarty読み込み require_once 'Smarty.class.php'; $smarty = new Smarty(); // Smartyディレクトリ設定 $smarty->template_dir = dirname(__FILE__) . "/templates/"; ←テンプレートのディレクトリ指定 $smarty->compile_dir = dirname(__FILE__) . "/templates_c/"; ←コンパイルファイルのディレクトリ指定
4.動作確認
テンプレートを作成してそれを読み込んで動作確認。
テンプレートの読み込みは、
// テンプレート読み込み $smarty->display('index.tpl');
テンプレートには適当にhtml文を書いて確認。
※出たエラーと対策
Fatal error: Smarty error: unable to write to $compile_dir '/home/sato/public_html/training/etc/templates_c'. Be sure $compile_dir is writable by the web server user. in /usr/local/lib/Smarty-2.6.26/libs/Smarty.class.php on line 1093
Webサーバーユーザー(apache実行ユーザー)にtemplates_cの書込権限がない。
Warning: include(/home/.../templates_c//%%AB^AB1^AB16ECA7%%manager.tpl.php) [function.include]: failed to open stream: Permission denied in /usr/local/lib/Smarty-2.6.26/libs/Smarty.class.php on line 1256
Webサーバーユーザー(apache実行ユーザー)にtemplates_cの読込権限がない。
・対応
chmod 770 templates_c
templates_cの所有者と所有グループに全ての権限を与えることで対応
もしこれでもエラーが出るなら、
templates_cにapache実行ユーザー(wwwとか)に権限がない。
所有グループにapache実行ユーザーを追加、もしくは変更する。
# chown user:www ../templates_c/