自定义模板资源 {#resources.custom}
您可以使用 PHP 能够访问的任何可能的源来检索模板:数据库、套接字、文件等。您可以通过编写资源插件函数并将它们注册到 Smarty 来实现这一点。
请参阅 资源插件 部分,了解更多您需要提供的函数信息。
注意
注意,您不能覆盖内置的
file:资源,但您可以通过在另一个资源名下注册来提供以某种其他方式从文件系统获取模板的资源。
<?php
/**
* MySQL 资源
*
* 基于自定义API的资源实现,使用
* MySQL作为Smarty的模板和配置的存储资源。
*
* 表定义:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
* `name` varchar(100) NOT NULL,
* `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
* `source` text,
* PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
*
* 演示数据:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
// PDO 实例
protected $db;
// 准备好的 fetch() 语句
protected $fetch;
// 准备好的 fetchTimestamp() 语句
protected $mtime;
public function __construct() {
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
throw new SmartyException('Mysql 资源失败:' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
$this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name');
}
/**
* 从数据库获取模板及其修改时间
*
* @param string $name 模板名
* @param string $source 模板源
* @param integer $mtime 模板修改时间戳(epoch)
* @return void
*/
protected function fetch($name, &$source, &$mtime)
{
$this->fetch->execute(array('name' => $name));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$source = $row['source'];
$mtime = strtotime($row['modified']);
} else {
$source = null;
$mtime = null;
}
}
/**
* 从数据库获取模板的修改时间
*
* @note 实现此方法是可选的。只有在可以比加载完整的模板源更快地访问修改时间时才实现它。
* @param string $name 模板名
* @return integer 时间戳(epoch)模板被修改的时间
*/
protected function fetchTimestamp($name) {
$this->mtime->execute(array('name' => $name));
$mtime = $this->mtime->fetchColumn();
$this->mtime->closeCursor();
return strtotime($mtime);
}
}
require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->registerResource('mysql', new Smarty_Resource_Mysql());
// 从php脚本使用资源
$smarty->display("mysql:index.tpl");
?>
从 Smarty 模板内部使用:
{include file='mysql:extras/navigation.tpl'}