专注于高品质PHP技术等信息服务于一体 [STIEMAP] [RSS]

百度提供的广告:
PHP
当前位置:首页 > 技术文档 > PHP >  > 
Smarty如何扩展函数功能

  Smarty 是目前业界最著名的PHP模板引擎之一。具有良好的可扩展性,与灵活性。轻量级模板引擎。目前有75%左右的PHP项目都采用此模板引擎,灵性的函数,简单的无素迭代。

  Smarty如何扩展函数功能:

在Smarty plugins目录下有很多php文件。

  • functions 函数插件
  • modifiers 修饰插件
  • block functions 区块函数插件
  • compiler functions 编译函数插件
  • prefilters 预滤器插件
  • postfilters 补滤器插件
  • outputfilters 输出过滤插件
  • resources 资源插件
  • inserts 嵌入插件

  有一些PHP开源的程序,采用的是变量注入型如ecshop 代码,不利于代码重用。


/**
 * 获得最新的文章列表。
 *
 * @access  private
 * @return  array
 */
function index_get_new_articles()
{
    $sql = 'SELECT a.article_id, a.title, ac.cat_name, a.add_time, a.file_url, a.open_type, ac.cat_id, ac.cat_name ' .
            ' FROM ' . $GLOBALS['ecs']->table('article') . ' AS a, ' .
                $GLOBALS['ecs']->table('article_cat') . ' AS ac' .
            ' WHERE a.is_open = 1 AND a.cat_id = ac.cat_id AND ac.cat_type = 1' .
            ' ORDER BY a.article_type DESC, a.add_time DESC LIMIT ' . $GLOBALS['_CFG']['article_number'];
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array();
    foreach ($res AS $idx => $row)
    {
        $arr[$idx]['id']          = $row['article_id'];
        $arr[$idx]['title']       = $row['title'];
        $arr[$idx]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ?
                                        sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
        $arr[$idx]['cat_name']    = $row['cat_name'];
        $arr[$idx]['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $arr[$idx]['url']         = $row['open_type'] != 1 ?
                                        build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']);
        $arr[$idx]['cat_url']     = build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']);
    }

    return $arr;
}

 $smarty->assign('new_articles',    index_get_new_articles());


代码可读性很差,如果,利用smarty的function扩展来完成这些操作,在模板页面上使用


{link listname="list"  row="21" linktype="1" typeid="1"}


来调用

plugins 下的 function.

link

.php
function smarty_

link

($params, &$smarty)
{
extract($params);
global $db;
//数据库操作略

}
$smarty->assign($link, $rs);
unset(
$rs);
}
在使用
{foreach from=$list item=list}
{/foreach}
来输出。
这样就不必在每个页面上写烦索的数据库操作代码了。 添加或修改功能很简单。