smarty中增加类似foreach的功能自动加载数据方法

2023-05-30,,

第一步:在Smarty_Compiler.class.php的_compile_tag函数中增加

复制代码 代码如下:

//加载数据的开始标签
case 'load':
 $this->_push_tag('load');
 return $this->_complie_load_start($tag_args);
 break;
//加载数据的结束标签
case '/load':
 $this->_pop_tag('load');
 return "<php endforeach; endif; unset(/$_from); ?>";
 break;
第二步:增加一个方法:

复制代码 代码如下:

/**
* 加载数据
* @param $tag_args
*/
function _complie_load_start($tag_args)
{
 $key = substr(md5($tag_args), 8, 16);   //根据参数生成一个特殊的变量名
 $attrs = $this->_parse_attrs($tag_args);
 //这里可以增加更多的处理
 $class = (!isset($attrs['class']) || empty($attrs['class'])) ? 'cls_crud' : trim($attrs['class']);
 (!isset($attrs['table']) || empty($attrs['table'])) && exit('`table` is empty!');
 $db = $class::factory(array('table' => substr($attrs['table'], 1, -1)));
 //定义新变量
 $this->_tpl_vars[$key] = $db->get_block_list(array(substr($attrs['where'], 1, -1)), $attrs['limit']);
 $tag_args = "from=/${$key} " . $tag_args;
 //调用foreach标签处理函数进行处理
 return $this->_compile_foreach_start($tag_args);
}
这样就可以在模板中使用load这个标签了。用法例如:

复制代码 代码如下:

{load table="test" where="`id`<100" limit=10 item=rec}
   ...
{/load}

$i = 0;
$t = microtime(true);
for(;$i<1000;$i++)
{
    $str = strtr(md5($i), $p2);
}
var_dump(microtime(true)-$t);    //0.085476875305176
$t = microtime(true);
for(;$i<2000;$i++)
{
    $str = preg_replace($p, '', md5($i));
}
var_dump(microtime(true)-$t);   //0.09863805770874
结果显示,strtr的效率比preg_replace高约15%左右。
趁着周末,查看了strtr php源码:

复制代码 代码如下:

PHP_FUNCTION(strtr)
{
        zval **str, **from, **to;
        int ac = ZEND_NUM_ARGS();
        //参数检查(zend_get_parameters_ex函数定义在zend_api.c文件中)
        if (ac < 2 || ac > 3 || zend_get_parameters_ex(ac, &str, &from, &to) == FAILURE) {
                WRONG_PARAM_COUNT;
        }
        //参数检查
        if (ac == 2 && Z_TYPE_PP(from) != IS_ARRAY) {
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "The second argument is not an array.");
                RETURN_FALSE;
        }
        convert_to_string_ex(str);
        /* shortcut for empty string */
        //宏Z_STRLEN_PP定义在zend_operators.h
        if (Z_STRLEN_PP(str) == 0) {
                RETURN_EMPTY_STRING();
        }
        if (ac == 2) {
                php_strtr_array(return_value, Z_STRVAL_PP(str), Z_STRLEN_PP(str), HASH_OF(*from));
        } else {
                convert_to_string_ex(from);
                convert_to_string_ex(to);
                ZVAL_STRINGL(return_value, Z_STRVAL_PP(str), Z_STRLEN_PP(str), 1);
                php_strtr(Z_STRVAL_P(return_value),
                                  Z_STRLEN_P(return_value),
                                  Z_STRVAL_PP(from),
                                  Z_STRVAL_PP(to),
                                  MIN(Z_STRLEN_PP(from),
                                  Z_STRLEN_PP(to)));
        }
}

smarty中增加类似foreach的功能自动加载数据方法的相关教程结束。

《smarty中增加类似foreach的功能自动加载数据方法.doc》

下载本文的Word格式文档,以方便收藏与打印。