ThinkPHP 自動(dòng)填充格式如下:
array(填充字段,填充內(nèi)容[,填充條件][,附加規(guī)則])
附加規(guī)則,可選,包括:
string:字符串,表示填充內(nèi)容為字符串(默認(rèn))。
function:使用函數(shù),表示填充的內(nèi)容是一個(gè)函數(shù)返回值。
callback:使用方法,表示填充的內(nèi)容是一個(gè)當(dāng)前 Model 的方法返回值。
field:字段,表示填充的內(nèi)容是一個(gè)其他字段的值。
ThinkPHP 自動(dòng)填充使用函數(shù)function
當(dāng)附加規(guī)則使用函數(shù)function填充時(shí),表示填充的內(nèi)容是一個(gè)函數(shù)返回值,這個(gè)函數(shù)可以是PHP內(nèi)置函數(shù)或用戶(hù)自定義函數(shù).
使用函數(shù)填充例子:
- class UserModel extends Model{
- protected $_auto = array (
- // 對(duì)password字段在所有情況下使用md5函數(shù)處理
- array('password','md5',3,'function'),
- // 對(duì)regdate字段在新增時(shí)寫(xiě)入當(dāng)前時(shí)間戳
- array('regdate','time',1,'function'),
- // 對(duì)regip字段在新增時(shí)寫(xiě)入用戶(hù)注冊(cè)IP地址
- array('regip','get_client_ip',1,'function'),
- // 對(duì)username字段在新增時(shí)使用自定義getName函數(shù)
- array('username','get_name',1,'function'),
- );
- }
在上面的例子中,使用的 md5 和 time 為 PHP 內(nèi)置函數(shù),填充結(jié)果為 md5($_POST['password']) 值和 time() 函數(shù)值,get_client_ip 和 get_name 為 Common/common.php 自定義函數(shù).
get_name 函數(shù)將用戶(hù)名加上 th_ 前綴,參考如下:
- function get_name($name){
- return 'th_'.$name;
- }
如果函數(shù)需要參數(shù),則將填充字段作為參數(shù),如上面的 md5 和 get_name 函數(shù)填充.
ThinkPHP 自動(dòng)填充使用方法callback
當(dāng)使用方法 callback 填充時(shí),表示填充的內(nèi)容是一個(gè)當(dāng)前 Model 的方法返回值,使用 callback 填充例子:
- class UserModel extends Model{
- protected $_auto = array (
- // 對(duì)username字段在新增時(shí)回調(diào)getName方法
- array('username','getName',1,'callback'),
- );
- }
getName方法將用戶(hù)名加上 th_ 前綴,參考如下:
- class UserModel extends Model{
- // 將傳入的username加上th_前綴
- function getName(){
- return 'th_'.$_POST['username'];
- }
- }
注:上述例子將 username 字段前自動(dòng)加上 th_ 前綴而填充到 username 中,僅是為了說(shuō)明自動(dòng)填充使用函數(shù)或回調(diào)方法的用法,可能并無(wú)實(shí)際生產(chǎn)意義.
新聞熱點(diǎn)
疑難解答
圖片精選