LoginSignup
3
2

More than 3 years have passed since last update.

Smartyを使ってみる

Last updated at Posted at 2020-04-05

1 インストール

1 download
 以下のサイトよりダウンロードします。
 http://www.smarty.net/

2 インストール
 ダウンロードしたzipを解凍します。使うのはlibsフォルダのみです。
 DocumentRootにsampleフォルダを作成しサンプルアプリを置くものとして

 htdocs + sample
      └ libs      <- ダウンロードしたsmartyのlibs

 ※libsを複数プロジェクト共通で利用する場合は、
  c:\smarty3\libs 等適当な場所へ配置しましょう。

3 設定
 smartyのlibsを共通で使う場合は、php.iniのinclude_pathの設定を行います。
";"を削除し、";c:\smarty3\libs"等と追記します。

php.ini
; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
 ↓
include_path = ".:/php/includes:/usr/local/lib/smarty3/libs"
;
; Windows: "\path1;\path2"
;include_path = ".;c:\php\includes"
 ↓
include_path = ".;c:\php\includes;c:\smarty3\libs"

 その他フォルダを作成します。
 htdocs + sample
      ├ libs ← ダウンロードしたsmartyのlibs
      ├ templates ← 空のフォルダを作成
      ├ templates_c ← 空のフォルダを作成
      ├ cache ← 空のフォルダを作成
      └ configs ← 空のフォルダを作成

2 sampleアプリケーション作成

 sampleフォルダにテンプレートとプログラムを作成します。

sample.tpl
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$msg}</h2>

</body>
</html>
sample.php
<?php
require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = dirname(__FILE__).'/templates';
$smarty->compile_dir  = dirname(__FILE__).'/templates_c';
$smarty->config_dir   = dirname(__FILE__).'/configs';
$smarty->cache_dir    = dirname(__FILE__).'/cache';

$smarty->assign('msg','Hello World!');
$smarty->display('sample.tpl');

?>

3 設定ファイルを使う(Smarty3)

 プログラムから設定ファイルを読み込んでみます。
 まずは、configs/sample.confを作り定義します。

sample.conf
# global
url = "www.hoge.com"
title = "Smarty"

[mysql]
DSN = "mysql:dbname=sample_db; host=localhost; charset=utf8"
USER = "user1"
PASS = "user1pass"

 そして、呼出側しは

sample.php
 :
//設定ファイル読込み
$smarty->configLoad('sample.conf');
//取得
$url = $smarty->getConfigVars('url');
//テスト表示
echo "url = ".$url."<br />";

//設定ファイル読込み(セクション)
$smarty->configLoad('sample.conf', 'mysql');
//取得
$dsn = $smarty->getConfigVars('DSN');
//テスト表示
echo "dsn = ".$dsn."<br />";

$smarty->display('sample.tpl');

4 DBからの一覧表示(PDO)

 DBのm_syainテーブルを全件取得し一覧表示してましょう。
 まずは、DBまわり用のクラス

CDbAccess.php
<?php

class DbAccess {
    private $pdo;

    /**
    * コンストラクタ

    * @param $smarty smartyオブジェクト
    */
    public function __construct($smarty){
        try {
            //configs/sample.confより設定取得
            $smarty->configLoad('sample.conf', 'mysql');
            $dsn = $smarty->getConfigVars('DSN');
            $user = $smarty->getConfigVars('USER');
            $pass = $smarty->getConfigVars('PASS');

            //PDOインスタンス生成
            $this->pdo = new PDO($dsn, $user, $pass);
            //接続語にオプション指定
            //(エラー発生時に例外をスローする指定)
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        catch(PDOException $Exception) {
            self::abort('エラー:' . $Exception->getMessage());
        }
    }

    /**
    * クローズ処理
    */
    public function close(){
        try {
            $this->pdo = null;
        }

        catch(PDOException $Exception) {
            //エラーは無視
        }
    }

    /**
    * テーブルデータ取得
    * 
    * @return テーブルデータ一覧
    */
    public function get_list(){
        try {
            //m_syainテーブルより全件取得
            $sql = "select * from m_syain where del_flg <> :delflg";
            $stt = $this->pdo->prepare($sql);
            $stt->execute(array(':delflg'=>'1'));
            //$sql = "select * from m_syain where del_flg <> ?";
            //$stt = $this->pdo->prepare($sql);
            //$stt->execute(array('1'));

            if ($list = $stt->fetchAll(PDO::FETCH_ASSOC) ){
                return $list;
            }
        }

        catch(PDOException $Exception) {
            self::abort('エラー:' . $Exception->getMessage());
        }
    }

    /**
    * フィールド名一覧取得
    * 
    * @return フィールド名一覧
    */
    public function get_keys(){
        try {
            $sql = 'show columns from m_syain';
            $stt = $this->pdo->prepare($sql);
            $stt->execute();

            while ($column = $stt->fetch(PDO::FETCH_ASSOC) ){
                $keys[] = $column['Field'];
            }
        }

        catch(PDOException $Exception) {
            self::abort('エラー:' . $Exception->getMessage());
        }
        finally {
            return $keys;
        }
    }

    /**
    * die()文字化け対策
    */
    private function abort($status=0) {
        if (is_string($status) && !headers_sent()) {
            //ヘッダにcharset追加
            header('Content-Type: text/plain; charset=UTF-8');
        }
        die($status);
    }
}

 呼出し側は

CDbAccess.php
<?php
 :
require_once ("CDbAccess.php");
 :
$smarty = new Smarty();
 :
$testdb = new DbAccess($smarty);
$keys = $testdb->get_keys();
$list = $testdb->get_list();
$values = [
       'title' => 'test',
       'head' => 'テスト',
       'keys' => $keys,
       'list' => $list
];

$smarty->assign ('values', $values);

//データベース接続終了
$testdb->close();
 :
$smarty->display('sample.tpl');
?>

 あとテンプレートは

template/sample.tpl
 :
    <h4>{$values.head}</h4>
    <table border=1 >
        {foreach $values.keys as $key}<th>{$key}</th>{/foreach}
        {foreach $values.list as $row}
            <tr>{foreach $row as $val}<td>{$val}</td>{/foreach}</tr>
        {/foreach}
    </table>
 :

5 エラー情報出力

 とりあえずphpファイルの先頭に以下の2行を入れる。

sample.php
<?php
ini_set('display_errors',1);        //1:エラー表示、0:非表示
error_reporting(E_ALL);         //エラー表示レベル(E_ALL & ~E_NOTICE等々指定)
 :

6 デバッグ

<?php
:
//デバッグコンソールを出す
$smarty->debugging = true;
:
//var_dumpで出力
var_dump($変数);
:
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2