手册 >> 开发指南 >> 自定义函数库

自定义函数库

在SpeedPHP框架开发中,开发者可以加入和使用自定义的函数库。

函数库通常是放置到一个专门的函数库文件中,然后在应用程序入口文件的全局位置中载入,然后在系统各处使用。

这里我们自定义了一个函数叫mydate,作用是提供个性化日期显示,并将其注册到模板中使用,以此为例说明如何放置自定义函数库。

例子下载:dev_diy_functions.zip

1. 自定义函数在应用程序目录(APP_PATH)的include目录中,文件名是functions.php,我们在入口文件的全局位置中载入。

require(SP_PATH."/SpeedPHP.php");
// 这里是入口文件全局位置
import(APP_PATH.'/include/functions.php');

spRun();

2. 载入后,直接可以使用,本例中是在/index.php?c=main&a=show中直接使用mydate函数

	function show(){
		header("Content-type: text/html; charset=utf-8"); // 直接输出UTF8
		echo mydate(strtotime("-1 day")); // 直接显示mydate函数的结果
		echo "<p><a href="".spUrl('main','index')."">模板显示</a></p>";
	}

3. 在functions.php中,我们使用spAddViewFunction来把mydate注册到模板中,由于模板函数的格式和普通函数有些不同,所以加入一个tpl_mydate函数来对mydate进行一下封装。

// mydate函数
function mydate($time = null){
	if( null == $time )$time = time(); // 默认是当前时间
	if( $time > (time() - 3600) ){
		return "刚才";
	}elseif( $time > (time() - 3600 * 24) ){
		return "今天";
	}elseif( $time > (time() -  3600 * 24 * 2) ){
		return "昨天";
	}elseif( $time > (time() -  3600 * 24 * 3) ){
		return "前天";
	}else{
		return date("Y-m-d H:s", $time);
	}
}
// 将mydate注册到模板中使用,所以需要加入tpl_mydate函数进行一次封装
function tpl_mydate($params){
	return mydate($params['time']);
}
// 使用spAddViewFunction来注册,模板中使用thedate来进行调用
spAddViewFunction('thedate','tpl_mydate');

4. 这样,在模板中也可以使用该函数了,调用的方法如下,演示在/index.php?c=main&a=index中。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>自定义函数演示</title>
</head>
<body>
<p>显示第一个时间:<{thedate time=$first_time}></p>
<p>显示第二个时间:<{thedate time=$second_time}></p>
<p>显示第三个时间:<{thedate time=$third_time}></p>
<p><a href="<{spUrl c=main a=show}>">直接显示</a></p>
</body>
</html>

注意,本例也包括了在函数库中,使用spAddViewFunction来对函数进行注册,以便让函数可以在Smarty模板中使用。

建议将spAddViewFunction的注册放置在函数定义代码附近,这样有利于寻找模板函数定义。