2007年12月10日
SmartyでMySQLに登録したテンプレートを使用する
SmartyのテンプレートをDB(MySQL)で管理してみる。
休日はいろいろと試してみたい事を、シコシコ、、
今日は、「SmartyのテンプレートをDBで管理してみる」事をしました。
Smartyは便利なテンプレートエンジンなんですが、CMSを作るときなど、
テンプレートをファイルよりも、DBで管理出来るようにしたいものです。
本とか、ネットとかで調べていても、抽象的なコードがあるだけで、なかなかコピペで使えるようなコードがなかったんで
すが、参考にしつつMySql版で作ってみました。
DB----
DB内データ(テンプレートレコード)---
DBのテンプレートを呼び出してみる。
実行結果
休日はいろいろと試してみたい事を、シコシコ、、
今日は、「SmartyのテンプレートをDBで管理してみる」事をしました。
Smartyは便利なテンプレートエンジンなんですが、CMSを作るときなど、
テンプレートをファイルよりも、DBで管理出来るようにしたいものです。
本とか、ネットとかで調べていても、抽象的なコードがあるだけで、なかなかコピペで使えるようなコードがなかったんで
すが、参考にしつつMySql版で作ってみました。
DB----
CREATE TABLE tpl(
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
tpl_name varchar(255),
tpl_source text,
tpl_timestamp timestamp(15)
)
DB内データ(テンプレートレコード)---
INSERT INTO tpl(id,tpl_name,tpl_source,tpl_timestamp)
VALUES (NULL,'index.tpl','
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>リソースプラグイン(DB化)</title>
</head>
<body>
<p>ユーザー情報:</p>
名前:{$name}<br>
URL: <a href="{$url}">{$url}</a><br>
</body>
</html>
',NOW( ));
DBのテンプレートを呼び出してみる。
require_once('libs/Smarty.class.php');
// create object
$smarty = new Smarty;
$sv = "localhost";
$dbname = "camp";
$user = "root";
$pass = "mnc2002";
// これらの関数をアプリケーションに追加する
function db_get_template ($tpl_name, &$tpl_source, &$smarty_obj) {
$conn = mysql_connect($GLOBALS["sv"],
$GLOBALS["user"],$GLOBALS["pass"]) or die("接続エラー");
mysql_select_db($GLOBALS["dbname"],$conn) or die("接続エラー2");
$sqlstr = "SELECT * FROM tpl Where tpl_name = '".$tpl_name."'";
$result = mysql_query($sqlstr, $conn) or die("データ抽出エラー1");
mysql_close();
if(mysql_num_rows($result) != 0) {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$tpl_source = $row['tpl_source'];
return true;
} else {
return false;
}
}
function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) {
// $tpl_timestampに代入するためにデータベースを呼び出す
$conn = mysql_connect($GLOBALS["sv"],
$GLOBALS["user"],$GLOBALS["pass"]) or die("接続エラー");
mysql_select_db($GLOBALS["dbname"],$conn) or die("接続エラー2");
$sqlstr = "SELECT * FROM tpl Where tpl_name = '".$tpl_name."'";
$result = mysql_query($sqlstr, $conn) or die("データ抽出エラー1");
mysql_close();
if(mysql_num_rows($result) != 0) {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$tpl_timestamp =$row['tpl_timestamp'];
return true;
} else {
return false;
}
}
function db_get_secure($tpl_name, &$smarty_obj) {
// 全てのテンプレートがセキュアであると仮定する
return true;
}
function db_get_trusted($tpl_name, &$smarty_obj) {
// テンプレートから使用しない
}
// テンプレートリソース名"db"を登録する
$smarty->register_resource("db", array("db_get_template",
"db_get_timestamp",
"db_get_secure",
"db_get_trusted"));
// phpスクリプトからテンプレートリソースを使用する
$smarty->assign('name', 'TEST');
$smarty->assign('url', 'http://www.cms-camp.jp/');
$smarty->display("db:index.tpl");
?>
実行結果
リソースプラグイン(DB化)
ユーザー情報:
名前:TEST
URL: http://www.cms-camp.jp/
この記事へのトラックバックURL
http://okinawasanpo.ti-da.net/t1860324






日本の地域ブログ大集合!津々浦々の美味い・楽しいがここに!