ä½ å�¯ä»¥é€šè¿‡ä»»ä½•å�¯è®¿é—®çš„æ�¥æº�æ�¥æ��供模æ�¿ï¼Œå¦‚æ•°æ�®åº“,网络sockets,文件ç‰ï¼Œ 编写这些æ�¥æº�的资æº�æ�’件并将他们注册到Smarty。
��资��件。
Note
注æ„�ä½ ä¸�能覆盖内置的file:资æº�,
ä½†ä½ å�¯ä»¥è®¾è®¡ä¸€ä¸ªåŸºäºŽæ–‡ä»¶ç³»ç»Ÿçš„资æº�并为其注册å�¦ä¸€ä¸ªèµ„æº�å��称。
Example 16.10. U使用自定义资�
<?php
/**
* MySQL 资�
*
* 过自定义API,实现用MySQLæ�¥å˜å�–模æ�¿å’Œé…�置资æº�。
*
* 表定义:
* <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;
// prepared fetch() statement
protected $fetch;
// prepared fetchTimestamp() statement
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 Resource failed: ' . $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 引用的模�修改时间戳
* @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 模�被修改的时间戳
*/
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");
?>
在模æ�¿ä¸ï¼š
{include file='mysql:extras/navigation.tpl'}
