首页 > 编程技术 > php

php模板简单写法

发布时间:2016-11-25 16:03

这是一个简单的用php 实现的模板教程物。

class  TEMPLATE
   {
                  
              
                      private  $path = "." ;          #根目录        
                             
                   private $var;
                  
                   private $tplDir = "template"; #模板存储目录
                  
                   private $tplExt = "tpl";      #模板文件的后缀名
                  
                   private $tplId = 0 ;   #模板的ID号
                  
                   private $compileDir = "template_c";  #编译后的php文件存放目录
                  
                   private $isCache=false ; #是否用缓存 (默认不启动)
                  
                   private $cacheId = 1; #缓存文件ID号
                  
                   private $cacheLeftTime=3600; #缓存有效期 (默认保存3600秒)
                  
                   private $cacheDir = "cache"; #缓存文件存储目录
                  
                   private $autoRefresh = false ; #是否自动刷新
                  
                   private $pattern = array(
                  
                                           "/({dw:)s*includes*filename=s*"(.+..+)s*"s*(/})/i",#包含文件
                                           "/({dw:)s*field.(.+)s*(/})/i",#局部变量
                                           "/({dw:)s*global.(.+)s*(/})/i",#全局变量
                                           "/({dw:)s*foreachs*(.+)s*ass*(.+)s*(/})/i",#foreach 语句
                                           "/({dw:)s*ends*foreachs*(/})/i",           #foreach 结束
                                           "/({dw:)s*ifs*((.+))(/})/i",
                                           "/({dw:)s*elseifs*((.+))(/})/i",
                                           "/({dw:)s*elses*(/})/i",
                                           "/({dw:)s*ends*ifs*(/})/i",
                                                                
                                );
                  
                   private $replacement = array(
                  
                                           '<?php echo $this->inc_file("\2"); ?>',
                                           "<?php echo $\2;?>",
                                           "<?php global $\2;n echo $\2; ?>",
                                           "<?php foreach($\2 as $\3){ ?>",
                                           "<?php } ?>",
                                           "<?php if (\2) {  ?>" ,
                                           "<?php }else if(\2){ ?>",
                                           "<?php }else{ ?>",
                                           "<?php  } ?>",
                                          
                                          
                                          
                                          
                                                                                                  
                                                                   );
                  
                  
                   #构造函数
                  
                   function __construct($path = "", $tplDir="", $compileDir="",$isCache="",$cacheLeftTime="",$cacheDir="" ,$autoRefresh="")
                   {
                           $this->path = $path ? $path : $this->path ;
                          
                           $this->tplDir = $tplDir ? $tplDir : $this->tplDir ;
                          
                           $this->compileDir = $compileDir ? $compileDir : $this->compileDir ;
                          
                           $this->isCache = is_bool($isCache) ? $isCache : $this->isCache ;
                          
                           $this->cacheLeftTime = $cacheLeftTime ? $cacheLeftTime : $this->cacheLeftTime ;
                          
                           $this->cacheDir = $cacheDir ? $cacheDir : $this->cacheDir ;
                          
                           $this->autoRefresh = is_bool($autoRefresh) ? $autoRefresh : $this->autoRefresh ;
                   }
                  
                  
                   #兼容php4
                  
                   function TEMPLATE($path = "", $tplDir="", $compileDir="",$isCache="",$cacheLeftTime="",$cacheDir="" ,$autoRefresh="")
                   {
                           $this->__construct($path = "", $tplDir="", $compileDir="",$isCache="",$cacheLeftTime="",$cacheDir="" ,$autoRefresh="");
                   }
                   function  __get($property)
                   {
                           return $this->$property ;
                   }
                  
                  
                   function __set($property,$value)
                   {
                           return $this->$property = $value ;
                   }
                  
                  
                  
        #给模板中的变量赋值
        # $tplVal 模板中的变量名                  
                  
                   function assign($tplVal ,$value="")
                   {
                           if (is_array($tplVal))
                           {
                                   foreach ($tplVal as $key => $val)
                                   {
                                           if (!empty($key))
                                          
                                           $this->var[$key] = $val ;
                                   }
                           }
                           else {
                                   if (!empty($tplVal))
                                  
                                   $this->var[$tplVal] = $value ;
                           }
                   }
                  
                   #输出文件内容函数
                  
                   function display($tplFile,$tplId=0,$cacheId = 1,$cacheLeftTime="")
                   {
                           if (empty($tplFile)) die("Template "{$tplFile}" not exist !");
                          
                           $this->cacheId = $cacheId ?  md5($cacheId) : md5($this->cacheId);
                          
                           $cacheFile = $this->path. "/".$this->cacheDir."/".$tplFile.$this->cacheId ;
                          
                           if ($this->check_cache($cacheFile,$cacheLeftTime))  #当缓存文件存在且不过期时直接从缓存文件读取内容
                           {
                                   echo $this->read_file($cacheFile);
                           }else {
                          
                              $tpl = $this->path."/".$this->tplDir."/".$tplFile.".".$this->tplExt;
          
                              $tplContent = $this->read_file($tpl);   #读取模板文件的内容
          
                             $compileContent= $this->compile_file($tplContent); #对读取出来的文件进行编译
           
                             $this->tplId = $tplId ? $tplId : $this->tplId ;
           
                             $compileFile = $this->path."/".$this->compileDir."/".md5($this->tplId)."".$tplFile.".php";
           
                             $this->write_file($compileFile,$compileContent);#将编译后的内容写入相应的文件中;
                          
                           @extract($this->var);
                          
                        ob_start();
                          
                           include_once($compileFile);
                          
                           $content = ob_get_contents() ;
                          
                           ob_end_clean() ;
                          
                           if ($this->isCache){
                                                     
                            $this->write_file($cacheFile,$content) ;# 帮编译好的内容写入缓存文件
                           }
                          
                           echo $content ;
                          
                           }
                   }
                  
                  
/*                   function  trim_tag($content)
                   {
                           $content = str_replace($this->startTag,"",$content);
                          
                           $content = str_replace($this->endTag,"",$content);
                                  
                           //$content = trim($content);
                          
                           return $content ;
                   }*/
                  
                   # 编译文件函数
                  
                   function compile_file($content=null)
                   {
                          
                           $content = $content ? $content :die("Compile fail!") ;
                          
                           //$content = $this->trim_tag($content);
                          
                           $content = preg_replace($this->pattern,$this->replacement,$content);
                          
                           return $content;
                          
                   }
                  
                   #解析包含文件
                  
                   function inc_file($filename,$tplId="",$cacheId="",$cacheLeftTime="")
                   { 
                           $file = $this->path."/".$this->tplDir."/".$filename ;
                          
                           if (file_exists($file))
                           {
                                   $filename = str_replace(".".$this->tplExt,"",$filename);
                                  
                           return         $this->display($filename,$tplId,$cacheId,$cacheLeftTime);
                           }
                           else die("Template "{$filename}" not exist");
                   }
                          
                   #读取文件内容函数
                  
                   function  read_file($filename)
                   {
                           if (!file_exists($filename)) die("Read file fail") ;
                          
                           return file_get_contents($filename);
                   }
                  
                   #内容写入函数
                  
                   function write_file($filename,$content,$mode="wb")
                   {
                          
                           $filename = trim($filename);
                          
                           $content = $content ? stripslashes(trim($content)) : exit();
                          
                           if (!file_exists($filename))
                           {
                                   $array = explode("/",$filename);
                                  
                                   $count = count($array);
                                  
                                   $path = "";
                                  
                                   for ($i = 0 ; $i <$count-1 ; ++$i )
                                   {
                                           if(!file_exists($path .= $array[$i]."/"))
                                           {
                                                   mkdir($path,0777);
                                           }
                                   }
                           }
                           $handle = fopen($filename,$mode) ;
                          
                           fwrite($handle,$content);
                          
                           fclose($handle);
                          
                           return true;       
                   }
                  
                  
                  
                   # 清除缓存
                  
                   function clear_dir($dir="")
                   {
                          
                           $dir = $this->path."/".$dir;
                          
                           $handle = opendir($dir);
                          
                           if (file_exists($dir))
                           {
                                   while ($file = readdir($handle))
                                   {
                                           if ($file !="." && $file != "..")
                                  
                                           unlink($dir."/".$file);
                                   }
                          
                             closedir($handle);
                            
                             return true;
                           }
                          
                           else {
                                   return false;
                           }
                          
                          
                   }
                  
                   #清除所有缓存
                  
                   function clear_all_cache()
                   {
                           if ($this->clear_dir($this->cacheDir) && $this->clear_dir($this->compileDir))
                                  
          
                           return true;
                   }
                  
                  
                  
                   #检查缓存是否过期
                  
                   function check_cache($cacheFile,$cacheLeftTime="")
                   {
                          
                           $cacheLeftTime = $cacheLeftTime ? $cacheLeftTime : $this->cacheLeftTime;
                          
                           if (!file_exists($cacheFile)) return false ;
                          
                          $time = $this->get_time($cacheFile) + $cacheLeftTime ;
                          
                           if ($time <time())
                           {
                                   unlink($cacheFile);
                                  
                                  
                                  
                                   return false;
                           }
                          
                           return true;
                          
                   }
                  
                  
                  
                   # 获取文件最后编辑时间
                  
                   function get_time($filename)
                   {
                           if (!file_exists($filename)) return false;
                          
                           return filemtime($filename);
                   }
                  
                  
                  
   }
                  

 

  

php 切取图片代码

function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
 list($imagewidth, $imageheight, $imageType) = getimagesize($image);
 $imageType = image_type_to_mime_type($imageType);
 
 $newImageWidth = ceil($width * $scale);
 $newImageHeight = ceil($height * $scale);
 $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
 switch($imageType) {
  case "image/gif":
   $source=imagecreatefromgif($image);
   break;
     case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
   $source=imagecreatefromjpeg($image);
   break;
     case "image/png":
  case "image/x-png":
   $source=imagecreatefrompng($image);
   break;
   }
 imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
 switch($imageType) {
  case "image/gif":
     imagegif($newImage,$thumb_image_name);
   break;
       case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
     imagejpeg($newImage,$thumb_image_name,90);
   break;
  case "image/png":
  case "image/x-png":
   imagepng($newImage,$thumb_image_name); 
   break;
    }
 chmod($thumb_image_name, 0777);
 return $thumb_image_name;
}

下面来看看在很多程序语言中会使用到的class吧,现在会举个简单的实例来实现php class,类申明,class使用方法哦。

<?php
/*
 * Explorer! 函数库
 * 编写日期:2008-06-29
 * 最后更新:2008-07-18 2:08
 *
 */
class System{//系统部分
 function usr_level($name){
  $SQL = new MySQL();
  $SQL->Query("SELECT `level` FROM `members` WHERE `username` = '$name';");
  $SQL->NextRecord();
  $TMP = $SQL->GetRecord('level');
  $SQL->Free();
  return $TMP;
 }
 function channel_level($cid){
  $SQL = new MySQL();
  $SQL->Query("SELECT `level` FROM `channels` WHERE `id` = $id;");
  $SQL->NextRecord();
  $TMP = $SQL->GetRecord('id');
  $SQL->Free();
  return $TMP;
 }
 function uid2name($uid){
  $SQL = new MySQL();
  if($SQL->Query("SELECT `username` FROM `members` WHERE `uid` = $uid;")){
   $SQL->NextRecord();
   $TMP = $SQL->GetRecord('username');
   $SQL->Free();
   return $TMP;
  }else{
   return 0;
  }
 }
 function name2uid($name){
  $SQL = new MySQL();
  if($SQL->Query("SELECT `uid` FROM `members` WHERE `username` = '$name';")){
   $SQL->NextRecord();
   $TMP = $SQL->GetRecord('uid');
   $SQL->Free();
   return $TMP;
  }else{
   return 0;
  }
 }
 function sysinfo($Name){//获取系统信息
  $SQL = new MySQL();
  $SQL->Query("SELECT * FROM `sysinfo`;");
  $SQL->NextRecord();
  $TMP = $SQL->GetRecord($Name);
  $SQL->Free();
  return $TMP;
 }
 function find_member($name){//查找该用户(注册时需要)
  $SQL = New MySQL();
  $SQL->Query("SELECT * FROM `members` WHERE `username` = '$name';");
  $RS = $SQL->RowS();
  $SQL->Free();
  if($RS)
   return 1;
  else
   return 0;
 }
 function str_safe($str){//字符串安全过滤
  $str = str_replace($str,";",";");
  $str = str_replace($str,"'","‘");
  $str = str_replace($str,"/","/");
  $str = str_replace($str,"`","`");
  $str = str_replace($str,"\","\");
  return $str;
 }
 function GetMyIP()
 {
  if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
   $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
   $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
  elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
   $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
  elseif (getenv("HTTP_X_FORWARDED_FOR"))
   $ip = getenv("HTTP_X_FORWARDED_FOR");
  elseif (getenv("HTTP_CLIENT_IP"))
   $ip = getenv("HTTP_CLIENT_IP");
  elseif (getenv("REMOTE_ADDR"))
   $ip = getenv("REMOTE_ADDR");
  else
   $ip = "127.0.0.1";
  return $ip;
 }
 function Version(){
  return "1.0.9";
 }
}
class MySQL{//数据库部分
 var $DBServer = 'localhost';//服务器
 var $DBName = '';//数据库名称
 var $DBUser = '';//数据库用户
 var $DBPass = '';//数据库密码
 var $OnErrorResume = 1;//错误提示关闭
 var $LinkID = 0;//连接句柄
 var $QueryID = 0;//查询句柄
 var $ResultS = array();//查询结果集
 var $Error = '';//错误信息
 function Connect($Srv = "",$Usr = "",$Pass = "",$DB = ""){//连接数据库
  if($Srv == "") $Srv = $this->DBServer;
  if($Usr == "") $Usr = $this->DBUser;
  if($Pass == "") $Pass = $this->DBPass;
  if($DB == "") $DB = $this->DBName;
  if($this->LinkID == 0){
   $this->LinkID = @mysql_connect($Srv,$Usr,$Pass) or die("数据库连接失败,请联系管理员修复此问题。");
  }
  @mysql_select_db($DB,$this->LinkID) or die("数据库选择失败,请联系管理员修复此问题。");
  return $this->LinkID;
 }
 function Free(){//释放查询结果
  @mysql_free_result($this->QueryID);
  $this->QueryID = 0;
 }
 function RowS(){//查询到的记录总数
  if(!$this->QueryID) return 0;
  return @mysql_num_rows($this->QueryID);
 }
 function NextRecord(){//下一条记录
  if(!$this->QueryID) return 0;
  $this->ResultS = @mysql_fetch_array($this->QueryID);
 }
 function Seek($seek){
  if(!$this->QueryID) return 0;
  @mysql_data_seek($this->QueryID,$seek);
 }
 function Query($Sql){//执行查询
  if($Sql == "") return 0;
  if($this->LinkID == 0) $this->Connect();
  if($this->QueryID) $this->Free();//释放原来查询结果
  $this->QueryID = @mysql_query($Sql,$this->LinkID);
  $this->Error = mysql_error($this->LinkID);
  if(!$this->QueryID) exit("$Sql执行失败."); 
  return $this->QueryID; 
 }
 function GetRecord($Name){
  if(!$this->QueryID) return 0;
  return $this->ResultS[$Name];
 }
}
?>

php 读取 sogourank 与 ChinaRank信息

function sogouRank($domain)
{
 $rank = '';
 $pr = 0;
 $content = get_content('http://www.sogou.com/web?query='.$domain);
 if(preg_match("/</span>([0-9]{1,})</dd>/", $content, $matches))
 {
  $pr = intval($matches[1]);
  $width = ceil(65*$pr/100);
  $rank = '<img" width=100% src="./images/sg_left.gif" width="2" height="11" /><img" width=100% src="./images/sg_left_img.gif" width="'.$width.'" height="11" /><img" width=100% src="./images/sg_right_img.gif" width="'.(65-$width).'" height="11" /><img" width=100% src="./images/sg_right.gif" width="2" height="11" />';
 }
 $rank = '<a href="http://www.sogou.com/web?query=link%3A'.$domain.'" target="_blank" title="搜狗Rank:'.$pr.'">'.$rank.'</a> '.$pr;
 return $rank;
}

function ChinaRank($domain)
{
 $rank = '';
 $content = get_content('http://www.chinarank.org.cn/detail/Info.do?url='.$domain);
 if(preg_match("/<strong>排名</strong>(.*)</tr>/", $content, $matches))
 {
  $p = trim(str_replace('</td>', '', $matches[1]));
  $p = explode("<td>", $p);
  if(isset($p[1])) $rank.= ' 今日:'.$p[1];
  if(isset($p[2])) $rank.= ' 本周:'.$p[2];
  if(isset($p[3])) $rank.= ' 三月:'.$p[3];
 }
 $rank = '<a href="http://www.chinarank.org.cn/detail/Info.do?url='.$domain.'" target="_blank">'.$rank.'</a>';
 return $rank;
}

php 读取 alexa信息

function Alexa($domain)
{
 $alexa = '';
 $content = get_content('http://www.alexa.com/data/details/traffic_details?url='.$domain);
 if(preg_match("/3 mos. Change([sS]*?)</table>/", $content, $matches))
 {
  $change = strpos($matches[1], 'down_arrow.gif') ? '下降' : '上升';
  $p = strip_tags($matches[1], '<td>');
  $p = trim(str_replace(array("&nbsp;", "n", "</td>"), array('', '', ''), $p));
  $p = explode("<td>", $p);
  if(isset($p[1])) $alexa.= ' 今日:'.$p[1];
  if(isset($p[2])) $alexa.= ' 本周:'.$p[2];
  if(isset($p[3])) $alexa.= ' 本月:'.$p[3];
  if(isset($p[4])) $alexa.= ' '.$change.':'.$p[4];
 }
 if(preg_match("/Review for $domain:</span> (.*)<br>/", $content, $matches))
 {
  $alexa = $alexa.' 等级:'.$matches[1];
 }
 $alexa = '<a href="http://www.alexa.com/data/details/traffic_details?url='.$domain.'" target="_blank">'.$alexa.'</a>';
 return $alexa;
}

标签:[!--infotagslink--]

您可能感兴趣的文章: