PHP -> PEAR -> サンプル
Smarty+PEARサンプルプログラム(MVCモデル)
環境準備
・php5
・Smarty
・PEAR
全てubuntuのパッケージマネージャーでインストールした。
ディレクトリ構成
/www
xxxx.php
/cache ( $smarty->cache_dir )
/configs ( $smarty->config_dir )
xxxx.php
/templates ( $smarty->template_dir )
xxxx.tpl
/templates_c ( $smarty->compile_dir )
ソース
以下6つのファイルを使用する。
- index.php
- configs/config.php
- controller.php
- model.php
- view.php
- tmplates/list.tpl
index.php
<html>
<head>
$lt;meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<div align='center'>
<?php
include_once("./controller.php");
?>
</div>
</body>
</html>
include_once と require_once の違い。
include_onceはエラーになっても動作を継続する。
require_onceはエラーになった時点で動作を停止する。
このページの場合、エラーになっても</div></body></html>は
表示させなければならないので include_once を使用する。
config.php
<?php
define(DSN,"mysql://user:passwd@localhost/userdb");
?>
controller.php
<?php
require_once('./model.php');
require_once('./view.php');
$db = new model;
$view = new view;
$db->connect();
$sql = "select * from user";
$list =& $db->query($sql);
$view->display($list,'list.tpl');
?>
model.php
<?php
require_once('/usr/share/php/PEAR/DB.php');
require_once('./configs/config.php');
class model
{
/* constructor */
var $dbh;
function connect()
{
$this->dbh =& DB::connect(DSN);
if (PEAR::isError($this->dbh)) {
die($this->dbh->getMessage());
}
}
function query($sql)
{
$results = array();
$result =& $this->dbh->query($sql);
if (PEAR::isError($result)){
die($result->getMessage());
}
while($row = $result->fetchRow(DB_FETCHMODE_ASSOC)){
$results[] = $row;
}
$result->free();
$this->dbh->disconnect();
return $results;
}
}
?>
view.php
<?php
require_once('/usr/share/php/smarty/Smarty.class.php');
class view
{
/* constructor */
var $smarty;
function view()
{
$this->smarty = new smarty;
}
function display($list,$tmpl)
{
foreach($list as $row){
for($i=0;count($row)>0;$i++){
$this->smarty->append("colmn{$i}",array_shift($row));
}
}
$this->smarty->display($tmpl);
}
}
?>
list.tpl
<table border='1'>
<tr>
<td>ID</td>
<td>User Name</td>
<td>passwd</td>
</tr>
{section name="list" loop=$colmn0}
<tr>
<td>{$colmn0[list]}</td>
<td>{$colmn1[list]}</td>
<td>{$colmn2[list]}</td>
</tr>
{/section}
</table>