


Template class extracted from Kangsheng products (discuz)_PHP tutorial
/*template.class.php
@ Kangsheng Weibo Template Extraction Class I think this template is easy to use. Take some time to make it independently.by Lei Rijin
@ took a look at the ctt template. Is it similar to the phpcms template? ? ^_^ Hehe! ! !
@ Weibo http://weibo.com/lrjxgl
@ Good things are shared with everyone. If you have any questions about the extraction, please ask
@ The default template file is .htm
$tpl = new template ('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//Enabling rewrite requires server support
$tpl-> ;rewrite_rule=array(array("/index.php/"),array("index.html")); //rewrite rule
$tpl->assign("indexurl","index.php") ;
$tpl->assign("str","I am a string la la la");
$tpl->assign("ec","I was echoed out");
$tpl->assign("subhtml","{subtpl ttt} This is used to introduce a template file, this is to introduce ttt.htm");
$tpl->assign("a ",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
*/
if(!defined("CHARSET")) define("CHARSET","gb2312");//Character encoding
if(!defined("DIR_TPL")) define("DIR_TPL ","tpl");//Default template directory
if(!defined("DIR_DATA")) define("DIR_DATA","data");//Default data directory
if(!defined(" DEBUG")) define("DEBUG",0);//Default running mode
class template {
//note var
public $rewrite=false;//Whether to enable pseudo-static rewrite
public $rewrite_rule=array(); //Set pseudo-static rules
public $defaulttpldir;//Default template
public $tpldir;//Template directory
public $objdir;//Compilation cache directory
public $tplfile;//Template file
public $objfile;//Compile file
public $tplid=1;//Template number
public $currdir='default';//Current style directory
public $vars=array();//note variable table
public $removeblanks=false;//remove spaces
public $stdout='display';//output type
function __construct ($tplid, $currdir) {
$this->template($tplid, $currdir);
}
function template($tplid, $currdir) {
ob_start();
if(file_exists(DIR_TPL.'/'.$currdir)) {
$this->currdir = $currdir;
$this->tplid = $tplid;
} else {
$this->currdir = 'default';
$this->tplid = 1;
}
$this->defaulttpldir = DIR_TPL.'/default';
$ this->tpldir = DIR_TPL.'/'.$this->currdir;
$this->objdir = DIR_DATA.'/cache/tpl';
if(version_compare(PHP_VERSION, '5' ) == -1) {
register_shutdown_function(array(&$this, '__destruct'));
}
}
//note publlic
function assign($k, $v ) {
$this->vars[$k] = $v;
}
//note publlic
function display($file) {
extract($this-> vars, EXTR_SKIP);
include $this->getObj($file);
}
function getObj($file, $tpldir = '') {
$subdir = ($pos = strpos($file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos + 1) : $ file;
$this->tplfile = ($tpldir ? $tpldir : $this->tpldir).'/'.($subdir ? $subdir.'/' : '').$file.' .htm';
$this->objfile = $this->objdir.'/'.($tpldir ? '' : $this->tplid.'_').($subdir ? $subdir .'_' : '').$file.'.php';
//note default directory
if(@filemtime($this->tplfile) === FALSE) {
$ this->tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
//note Determine whether the comparison is expired
if(!file_exists($this->objfile) || DEBUG && @filemtime($this->objfile) tplfile)) {
$ this->compile();
}
return $this->objfile;
}
function getTpl($file) {
$subdir = ($pos = strpos($ file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos + 1) : $file;
$tplfile = $this->tpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
if(@filemtime($tplfile) === FALSE) {
$tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
return $tplfile;
}
function compile() {
$var_regexp = "@?\$[a-zA-Z_]w*(?:[[w."'[] $]+])*";
$vtag_regexp = "=(@?\$[a-zA-Z_]w*(?:[[w."'[]$]+])* )?>";
$const_regexp = "{([w]+)}";
$template = file_get_contents($this->tplfile);
for($i = 1; $ i if(strpos($template, '{subtpl') !== FALSE) {
if(DEBUG == 2) {
$template = str_replace( '{subtpl ', '{tpl ', $template);
} else {
$template = preg_replace("/[nrt]*{subtpls+([a-z0-9_:/]+)}[ nrt]*/ies", "file_get_contents($this->getTpl('\1'))", $template);
}
}
}
$remove = array(
'/(^|r|n)/*.+?(r|n)*/(r|n)/is',
'///note.+?(r|n)/i ',
'///debug.+?(r|n)/i',
'/(^|r|n)(s|t)+/',
'/(r |n)/',
);
$this->removeblanks && $template = preg_replace($remove, '', $template);
$template = preg_replace("//s", "{\1}", $template);
$template = preg_replace("/{($var_regexp)}/", " =\1?>", $template);
$template = preg_replace("/{($const_regexp)}/", "=\1?>", $template);
$template = preg_replace("/(?", $template);
$template = preg_replace("/=(@?\$[a-zA-Z_]w*)(([[\$[]w]+])+)?>/ies", "$this->arrayindex('\1', '\2')", $template);
$template = preg_replace("/{{eval (.*?)}}/ies", "$this->stripvtag(' \1?>')", $template);
$template = preg_replace("/{eval (.*?)}/ies", "$this->stripvtag(' \1?>')", $template);
$template = preg_replace("/[nrt]*{echos+(.+?)}[nrt]*/ies", "$this->stripvtag(' echo \1; ?>','')", $template);
$template = preg_replace("/{for (.*?)}/ies", "$this->stripvtag(' for(\1) {?>')", $template);
$template = preg_replace("/{elseifs+(.+?)}/ies", "$this->stripvtag(' } elseif(\1) { ?>')", $template);
for($i=0; $i$template = preg_replace("/{loops+$vtag_regexps+$vtag_regexps+$vtag_regexp}(.+?){/loop}/ies", "$this->loopsection('\1', '\2', '\3', '\4')", $template);
$template = preg_replace("/{loops+$vtag_regexps+$vtag_regexp}(.+?){/loop}/ies", "$this->loopsection('\1', '', '\2', '\3')", $template);
}
$template = preg_replace("/{ifs+(.+?)}/ies", "$this->stripvtag(' if(\1) { ?>')", $template);
$template = preg_replace("/{tpls+(w+?)}/is", " include $this->getObj("\1");?>", $template);
$template = preg_replace("/{tpls+(.+?)}/ise", "$this->stripvtag(' include $this->getObj("\1"); ?>')", $template);
$template = preg_replace("/{tmptpls+(w+?)}/is", " include $this->getObj("\1", $this->objdir);?>", $template);
$template = preg_replace("/{tmptpls+(.+?)}/ise", "$this->stripvtag(' include $this->getObj("\1", $this->objdir); ?>')", $template);
$template = preg_replace("/{else}/is", " } else { ?>", $template);
$template = preg_replace("/{/if}/is", " } ?>", $template);
$template = preg_replace("/{/for}/is", " } ?>", $template);
$template = preg_replace("/$const_regexp/", "=\1?>", $template);//note {else} 也符合常量格式,此处要注意先后顺序
$template = preg_replace("/(\$[a-zA-Z_]w+[)([a-zA-Z_]w+)]/i", "\1'\2']", $template);
$fp = fopen($this->objfile, 'w');
fwrite($fp, $template);
fclose($fp);
}
function arrayindex($name, $items) {
$items = preg_replace("/[([a-zA-Z_]w*)]/is", "['\1']", $items);
return "=$name$items?>";
}
function stripvtag($s) {
$vtag_regexp = "=(@?\$[a-zA-Z_]w*(?:[[w."'[]$]+])*)?>";
return preg_replace("/$vtag_regexp/is", "\1", str_replace("\"", '"', $s));
}
function loopsection($arr, $k, $v, $statement) {
$arr = $this->stripvtag($arr);
$k = $this->stripvtag($k);
$v = $this->stripvtag($v);
$statement = str_replace("\"", '"', $statement);
return $k ? " foreach((array)$arr as $k => $v) {?>$statement}?>" : " foreach((array)$arr as $v) {?>$statement } ?>";
}
function __destruct() {
$content = ob_get_contents();
//处理 rewrite
if($this->rewrite) {
$arr=$this->rewrite_rule;
$s=$arr[0];
$e=$arr[1];
$content=preg_replace($s,$e,$content);
}
ob_end_clean();
echo $content;
}
}
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//开启rewrite 需要服务器支持
$tpl->rewrite_rule=array(array("/index.php/"),array("index.html")); //rewrite规则
$tpl->assign("indexurl","index.php");
$tpl->assign("str","我是字符串啦啦啦");
$tpl->assign("ec","我是被echo出来的");
$tpl->assign("subhtml","{subtpl ttt}这是用来引入一个模板文件的,这个就是引入ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
?>
新建 tpl/default/index.html
1 .String assignment:
{$str}
2. Array assignment:
{loop $a $v }{$v},{/loop}
or
{loop $a $key $val }{$val},{/loop}
3.{ $subhtml}
{subtpl ttt}
4. Originally I was {$indexurl } and now I have been turned into index.php
5. I can also echo
{echo $ec}
6. In fact, I can also add, subtract, multiply and divide 6*7*8
{echo 6*7*8;}
7. These are the commonly used ones, what else don

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!
