


The code explanation is similar to the principle of smart template engine
先贴下目录结构:
<code> ls compiled/ index.php source/ ss.class.PHP compiled 模版编辑后的目录 index.php source 模版源文件夹 ss.clsss.php 山寨类smarty文件夹 </code>
<code>ss.clsss.php </code>
<code><?php class Template{ private $templateDir;//源文件文件夹 private $compileDir;//编译之后文件夹 private $leftTag="{#";//需要替换的左边标记 private $rightTag="#}";//需要替换的左边标记 private $templateExtName=".html"; private $currentTemp;//当前正在编译的模版文件名 private $outputHtml;//正在读取的模版文件 private $varPool=array();//模版变量池 public function__construct($templateDir,$compileDir,$leftTag=null,$rightTag=null,$templateExtName=null){ $this->templateDir=$templateDir; $this->compileDir=$compileDir; if(!empty($leftTag))$this->leftTag=$leftTag; if(!empty($rightTag))$this->rightTag=$rightTag; if(!empty($templateExtName))$this->templateExtName=$templateExtName; } // 把用到的变量放入到变量池子中 public function assign($tag,$var){ $this->varPool[$tag]=$var; } // 取出一条变量,用于下面的str_replace正则替换 public function getVar($tag){ return $this->varPool[$tag]; } //获取模版源文件 public function getSourceTemplate($templateName){ $this->currentTemp=$templateName; // 拼接完整文件名 $sourceFileName=$this->templateDir.$this->currentTemp.$this->templateExtName; $this->outputHtml=file_get_contents($sourceFileName); } // 编译 public function compileTemplate($templateName=null){ // 获取当前需要编译的模版 $templateName=empty($templateName)?$this->currentTemp:$templateName; // $pattern='/\{#(\$[a-zA-Z_]\w+)#\}/';// 符合php变量命名 //preg_quote 可对用户界定的左右定界符中出现. \ + * ? [ ^ ] $ ( ) { } = ! | : -进行转义 $pattern="/".preg_quote($this->leftTag); //前后加上空格匹配任意次匹配类似<h1 id="name">{# $name #}</h1> $pattern.=' *\$([a-zA-Z_]\w*) *'; $pattern.=preg_quote($this->rightTag)."/"; $this->outputHtml=preg_replace($pattern, '<?php echo $this->getVar(\'$1\');?>', $this->outputHtml);// $1写成\\1也可以 // 注意不要用双引号,会解析getvar Template::$getVar报notice错误 $this->outputHtml=preg_replace($pattern, "<?php echo $this->getVar(\\1);?>", $this->outputHtml); $compileFileName=$this->compileDir.md5($templateName).$this->templateExtName; file_put_contents($compileFileName, $this->outputHtml); } // 输出 public function display($templateName=null){ $templateName=empty($templateName)?$this->currentTemp:$templateName; include($this->compileDir.md5($templateName).$this->templateExtName); } }</code>
简单调用如下:(index.php
中内容)
<code><?php include('ss.class.php'); $basedir=str_replace('\\', '/', dirname(__FILE__));//兼容linux等区分大小写平台 $test=new Template($basedir."/source/",$basedir."/compiled/"); $test->assign('name','iamtb'); $test->assign('pageTitle','tbtbt'); $test->getSourceTemplate('index'); $test->compileTemplate('index'); $test->display('index'); </code>
以上就介绍了代码解释类似smart模版引擎原理,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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

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 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
