Smartyでホームページを作る – 実践編
index.phpのみでホームページを制御する
Smartyについて連々と書いてきましたが、デザイナー側はこのカテゴリーの記事を読んで使えるようになれば、十分だと思います。テンプレートはあくまでページデザインを担うものとして扱い、処理はPHP側で行うのが理想です。
さて、今度はプログラマー側のお話しです。テンプレートが変わる度にPHPを書いていてはたまったもんじゃ有りません。それならHTMLで作ってしまった方が早いです。ですので、index.phpのみでページ切り替え(テンプレート変更)を行うよう考えてみます。
サンプルは、ヘッダー、フッターの他に、以下の3枚のテンプレートを作りました。
Index01.tpl
Index02.tpl
Index03.tpl
URLによって、テンプレートを切り替えます。
mod_rewriteとフレンドリーURL
PHP側の解説を始める前に、サンプルの各ページのURLが以下のようになっているのが判ると思います。
./Sample/Smarty/Index02.html
これ実は以下のURLでもアクセス出来ます。
./Sample/Smarty/?mode=Index02
ただ、これじゃURLとして味気ないですし、SEO的にも宜しくないです。真偽は置いておき、Googleなんかはページの拡張子が.htmlの方が良いとかどうとか。
この、?mode=Index02をIndex02.htmlにするには、mod_rewriteというものを使います。.htaccessに以下のように書きます。
1 2 3 4 5 6 | DirectoryIndex index.php RewriteEngine on #RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)$ index.php?mode=$1 [L] |
mod_rewriteは色々な書き方が有りますし、サーバーによっても書き方が変わりますので、あくまで一例です。詳しい説明は省きますが、URLの末尾に付いた文字を $_GET[‘mode ‘]という変数に格納してindex.phpに渡すように書かれています。
これでも表示出来ます。
index.phpの処理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <?php mb_language( "Japanese" ); mb_internal_encoding( "UTF-8" ); require_once ( 'Smarty/Smarty.class.php' ); /* * テンプレート表示クラス */ class SmartyControll{ var $Smarty ; var $Template ; function setTemplates(){ $smarty = $this -> Smarty; $smarty ->display( 'smarty_Header.tpl' ); //ヘッダーのテンプレート if ( $this -> Template) $smarty ->display( $this -> Template); //コンテンツのテンプレート $smarty ->display( 'smarty_Footer.tpl' ); //フッターのテンプレート } } /* * コントローラー */ class controller{ var $post ; var $get ; function mode(){ $templates = null; if ( $_GET [ 'mode' ]): $mode = htmlspecialchars( $_GET [ 'mode' ] , ENT_QUOTES , "UTF-8" ); //URLの意図しない文字を変換 $mode = explode ( "." , $mode ); // Index**.html を . で区切って配列化 $templates = $mode [0]. '.tpl' ; //テンプレート名を定義 endif ; //Smartyを定義 $smarty = new Smarty; $smarty -> template_dir = 'tpl/' ; //テンプレートフォルダー $smarty -> compile_dir = 'cache/' ; //キャッシュフォルダー if ( $templates ): if ( file_exists ( "tpl/" . $templates ) == false): //****.tplが存在してるか確認 $templates = 'Index01.tpl' ; //無ければIndex01.tplを表示 endif ; else : $templates = 'Index01.tpl' ; endif ; $obj = new SmartyControll; $obj -> Smarty = $smarty ; $obj -> Template = $templates ; $obj -> setTemplates(); exit ; } } $obj = new controller; $obj -> mode(); ?> |
やっていることは単純で、$_GET[‘mode’]をドットで配列化し、Index02などの文字を得ます。それと同じ名前のテンプレート(Index02.tpl)があれば、そのテンプレートを表示、無ければIndex01.tplを表示といった処理です。プログラマーはこれをたたき台にし、例えば class Index01 というクラスを作り、ページ内の処理を書いていくなど。こんな感じで、プログラマはデザインが上がってくる前に、URLに応じた処理を書く事が出来ますので、工数削減になります。