Skip to content

资源 {/programmers/plugins/plugins-resources/}

资源插件是为 Smarty 提供模板源或 PHP 脚本组件的通用方式。资源的一些示例包括:数据库,LDAP,共享内存,套接字等。

自定义资源可以放在你的$plugins_dir中的resource.foobarxyz.php文件中,或者在运行时使用registerResource()注册。无论哪种情况,你都可以通过在你正在处理的模板前加上它的名称来访问该资源:foobarxyz:yourtemplate.tpl

如果资源的模板不应通过 Smarty 编译器运行,自定义资源可以扩展Smarty_Resource_Uncompiled。资源处理器必须实现函数renderUncompiled(Smarty_Internal_Template $_template)$_template是对当前模板的引用,包含所有分配的变量,实现者可以通过$_template->smarty->getTemplateVars()访问。这些资源只是将其渲染的内容回显到输出流。如果 Smarty 实例相应地配置了,渲染的输出将被输出缓存。参见libs/sysplugins/smarty_internal_resource_php.php中的示例。

如果资源的编译模板不应在磁盘上缓存,自定义资源可以扩展Smarty_Resource_Recompiled。这些资源每次访问时都会被编译。这可能是一个昂贵的开销。参见libs/sysplugins/smarty_internal_resource_eval.php中的示例。

以下是一个基于自定义 API 的资源实现示例,该示例将 MySQL 用作 Smarty 的模板和配置的存储资源:

<?php
/**
 * MySQL Resource
 *
 * Resource Implementation based on the Custom API to use
 * MySQL as the storage resource for Smarty's templates and configs.
 *
 * Table definition:
 * <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>
 *
 * Demo data:
 * <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 instance
    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');
    }

    /**
     * Fetch a template and its modification time from database
     *
     * @param string $name template name
     * @param string $source template source
     * @param integer $mtime template modification timestamp (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;
        }
    }

    /**
     * Fetch a template's modification time from database
     *
     * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source.
     * @param string $name template name
     * @return integer timestamp (epoch) the template was modified
     */
    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());

// using resource from php script
$smarty->display("mysql:index.tpl");
?>

并在 Smarty 模板内部使用:

{include file='mysql:extras/navigation.tpl'}

参见 registerResource(), unregisterResource().