:::
5. 用Smarty樣板引擎將資料與前端結合
- Smarty的官網在:http://www.smarty.net
- Smarty 4.x 的文件在:https://smarty-php.github.io/smarty/4.x/
- 用composer安裝Smarty,按 Ctrl+` 開啟終端機,並貼上:
composer require smarty/smarty - 建立四個Smarty需要的目錄,亦可按 Ctrl+` 開啟終端機,並貼上:
mkdir templates mkdir templates_c mkdir configs mkdir cache- templates:放置原始樣板的目錄(一定會用到)
- templates_c:編譯後的樣板目錄(需可寫入)
- configs:設定目錄(不見得會用到)
- cache:樣板快取目錄(需可寫入)
- 要使用Smarty佈景引擎,必須先引入自動載入檔,然後實體化一個佈景引擎:
require_once 'vendor/autoload.php'; // 啟用Smarty樣板引擎 $smarty = new Smarty(); - 由於前後臺都會用到佈景引擎,所以,我們經之整合至
header.php中:<?php require_once 'config.php'; require_once 'vendor/autoload.php'; // 啟用Smarty樣板引擎 $smarty = new Smarty(); // 建立資料庫連接 $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset"; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch (PDOException $e) { echo "資料庫連接錯誤:" . $e->getMessage(); }
4-9 把設定值也獨立成 config.php