search
HomeBackend DevelopmentPHP TutorialA simple template class (PHP)_PHP tutorial

A simple template class (PHP)_PHP tutorial

Jul 13, 2016 pm 05:51 PM
phpandlandoperatedatatemplateofSimplekindwere ableproject

With a data manipulation class, the project can only simply manipulate data, but to be able to display beautiful pages together with the artist, a better template engine is needed. Compared with a relatively large template engine like SMARTY, I think the following one is really much smaller.

I saw this template class on the Internet before, and it was well written, so I quoted it. I don’t know who the author is yet, so I will talk about the principle of this class first.

First of all, this class has only a simple regular parser. But basically it can be used. If it can be expanded on this basis, I believe this little thing will have great development. Comrades with the same hobbies are invited to join in strengthening it. I'll drop the bricks right now.

template.class.php

[html]
class template{
       
//Array stored in variables
Private $vars = array();
//Template directory
Public $template_dir = './template/';
//Cache directory
Public $cache_dir = './cache/';
//Compile directory
Public $template_c_dir = './template_c/';
//Template file
Public $template_file = '';
//Left connector
Public $left_delimiter = ' //Right connector
Public $right_delimiter = '}>';
//Compile file
Private $template_c_file = '';
//Cache files
Private $cache_file = '';
//Cache time
Public $cache_time = 0;
       
//Built-in parser
Private $preg_temp = array(
          '~~i'
=> '', //
                                                                  '~~i'
=> '', //
                                                                 '~~i'
=> '', //
                                                                  '~~i'
=> '_include($2); ?>', // <?php include('inc/top.php'); ?>
                                                        '~~' => '', //
                                                        '~~' => '', //
                                                        '~=s*~' => ' );
       
/**
*Constructor
​​*/
Public function __construct(){
If(defined('TMP_PATH')){
                 $this->template_c_dir = TMP_PATH . 'template_c/';
$ This-& gt; cache_dir = tmp_path. 'Cache/';
         } 
}  
       
/**
*Variable assignment
*@param $key mixed key name
*@param $value mixed value
​​*/
Public function assign($key, $value = ''){
If(is_array($key)){
$this->vars=array_merge($key,$this->vars);
         } 
        else{
$this->vars[$key]=$value;
         } 
}  
       
/**
*Show page
*@param $file string template file name
​​*/
Public function display($file){
echo $this->fetch($file);
}  
       
/**
*Return to cache content
*@param $file string template file name
*@return $content string cache content
​​*/
Public function fetch($file){
           $this->template_file = $file;
          $desc_template_file = $this->template_dir .$file;
          $desc_content = $this->readfile($desc_template_file);
                                   
          $template_c_file_time= filemtime($desc_template_file);
//If the cache time is exceeded, compile
If($this->cache_time $this->complie($this->token($desc_content));
         } 
//Get the contents of the cache area below
         ob_start();
                                   
@extract($this->vars , EXTR_OVERWRITE);
include ($this->template_c_dir . $this->template_c_file);
                                   
         $content = ob_get_contents();
         ob_end_clean();
                                   
//$this->store_buff($content);
         return $content;
}  
       
/*
*Replace the delimiter, and replace the content of the parser
*@param $content string read content
*@return $token_content string replaced content
*/
Public function token($content){
         $token_content = $content;
If($left_delimiter != '                $token_content = str_replace($left_delimiter, '                 $token_content = str_replace($right_delimiter, '}>' , $token_content);
         } 
          $token_content = preg_replace(array_keys($this->preg_temp), $this->preg_temp, $token_content);
         return $token_content;
}  
       
/*
*Generate storage
*@param $content string read content
* *
         
Public function store_buff($content){
$this->cache_file = md5($this->template_file) . $this->template_file . '.html';
$tempfile = $this->cache_dir . $this->cache_file;
           $fp = fopen($tempfile, 'w');
          fputs($fp,$content);
          fclose($fp);
          unset($fp);
}  
*/
       
/*
*Compile and save
*@param $content string read content
* *
*/
Public function complie($content){
$this->template_c_file = md5($this->template_file) . $this->template_file . '.php';
$tempfile = $this->template_c_dir . $this->template_c_file;
           $fp = fopen($tempfile, 'w');
          fputs($fp,$content);
          fclose($fp);
          unset($fp);
}  
       
/*
*Read the contents of the file
*@param $file string file name
*@return $content string file content
*/
Public function readfile($file){
If(file_exists($file)){
                 $fp = fopen($file, 'r');
               $content ='';
             while(!feof($fp)){
                       $content .= fgets($fp,4096);
                                                                                                                                                       fclose($fp);
               unset($fp);
                    return $content;                                        } 
        else{
exit($file . ' not exist!');
         } 
}  
       
/*
*Template nesting
*@param $file string file name
*@return string The absolute address of the file
*/
Public function _include($file){
If(file_exists($this->template_dir . $file)){
                return ($this->template_dir . $file);
         } 
        else{
echo "Template file does not exist";
exit;
         } 
}   www.2cto.com
}
?>

With this template, you can forget about those large templates. After all, your artist will not write so many SMARTY marks in his slice file, and as long as he cuts it, you can use it directly without modifying the images. , css, js address.

Author: tomyjohn


http://www.bkjia.com/PHPjc/478157.html

truehttp: //www.bkjia.com/PHPjc/478157.htmlTechArticleWith a data operation class, the project can only simply operate the data, but it must be able to be displayed together with the artist A beautiful page requires a better template engine. With SMA...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

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.