php tpl Template Engine Definition and Use Examples

  • 2021-12-19 06:02:01
  • OfStack

This article illustrates the definition and use of php tpl template engine. Share it for your reference, as follows:

tpl.php


<?php
namespace tpl;
/**
* Class Tpl
*/
class Tpl
{
  protected $view_dir;// Template file 
  protected $cache_dir;// Cache file 
  protected $lifetime;// Expired time 
  protected $vars = [];// Array for display variables 
   /**
   * Tpl constructor.
   * @param string $view_dir
   * @param string $cache_dir
   * @param string $lifetime
   */
  public function __construct($view_dir='', $cache_dir='', $lifetime='')
  {
    // If the template file is not empty, it is set, and if it is empty, it is the default value 
    if (!empty($view_dir)) {
      if ($this->check_dir($view_dir)) {
        $this->view_dir = $view_dir;
      }
    }
    // If the cache file is not empty, it is set, and when it is empty, it is the default value 
    if (!empty($cache_dir)) {
      if ($this->check_dir($cache_dir)) {
        $this->cache_dir = $cache_dir;
      }
    }
    // If the expiration time is not empty, it is set, and when it is empty, it is the default value 
    if (!empty($lifetime)) {
      $this->lifetime = $lifetime;
    }
  }
   /**
   *  The method of opening to the outside world 
   * @param string $name
   * @param string $value
   */
  public function assign($name, $value)
  {
    $this->vars[$name] = $value;// Save the passed parameters in an array as key-value pairs 
  }
   /**
   *  Test file 
   * @param $dir_path
   * @return bool
   */
  protected function check_dir($dir_path)
  {
    // If the file does not exist or is not a folder, create 
    if (!file_exists($dir_path) || !is_dir($dir_path)) {
      return mkdir($dir_path, 0777, true);
    }
    // If the file is unreadable or unwritable, set the mode 
    if (!is_writable($dir_path) || !is_readable($dir_path)) {
      return chmod($dir_path, 0777);
    }
    return true;
  }
   /**
   *  Presentation method 
   * @param $view_name
   * @param bool $isInclude
   * @param null $uri
   */
  public function display($view_name, $isInclude=true, $uri=null)
  {
    // Get the template file path through the passed-in file name 
    $view_path = rtrim($this->view_dir, '/') . '/' . $view_name;
    // Judge whether the path exists or not 
    if (!file_exists($view_path)) {
      die(' File does not exist ');
    }
    // Get the cached file name from the passed-in file name 
    $cache_name = md5($view_name . $uri) . '.php';
    // Slow down the cache file name to get the cache path 
    $cache_path = rtrim($this->cache_dir, '/') . '/' .$cache_name;
    // Judge whether the cache file exists, and if it does not exist, regenerate it 
    if (!file_exists($cache_path)) {
      $php = $this->compile($view_path);// Parse template file 
      file_put_contents($cache_path, $php);// Cache file regeneration 
    } else {
      // If the cache file exists, whether it expires or not is judged, and whether the template file is modified or not is judged 
      $is_time_out = (filectime($cache_path) + $this->lifetime) > time() ? false : true;
      $is_change = filemtime($view_path) > filemtime($cache_path) ? true : false;
      // If the cache file expires or the template file is modified, rebuild the cache file 
      if ($is_time_out || $is_change) {
        $php = $this->compile($view_path);
        file_put_contents($cache_path, $php);
      }
    }
    if ($isInclude) {
      extract($this->vars);// Parsing an array of passed-in variables 
      include $cache_path;// Display cache 
    }
  }
   /**
   *  Regular parsing template file 
   * @param string $file_name
   * @return mixed|string
   */
  protected function compile($file_name)
  {
    $html = file_get_contents($file_name);// Get template file 
    // Regular transformation array 
    $array = [
      '{$%%}' => '<?=$\1?>',
      '{foreach %%}' => '<?php foreach (\1): ?>',
      '{/foreach}' => '<?php endforeach ?>',
      '{include %%}' => '',
      '{if %%}' => '<?php if (\1): ?>',
      '{/if}' => '<?php endif ?>',
      '{for %%}' => '<?php for (\1): ?>',
      '{/for}' => '<?php endfor ?>',
      '{switch %%}' => '<?php switch (\1) ?>',
      '{/switch}' => '<?php endswitch ?>'
    ];
    // Traversing an array to generate a regular expression 
    foreach ($array AS $key=>$value) {
      // Regular expressions, 
      $pattern = '#' . str_replace('%%', '(.+?)' , preg_quote($key, '#')) . '#';
      if (strstr($pattern, 'include')) {
        $html = preg_replace_callback($pattern, [$this, 'parseInclude'], $html);
      } else {
        $html = preg_replace($pattern, $value, $html);
      }
    }
    return $html;
  }
   /**
   *  Deal with include Expression 
   * @param array $data
   * @return string
   */
  protected function parseInclude($data)
  {
    $file_name = trim($data[1], '\'"');
    $this->display($file_name, false);
    $cache_name = md5($file_name) . '.php';
    $cache_path = rtrim($this->cache_dir, '/') . '/' . $cache_name;
    return '<?php include "'.$cache_path.'" ?>';
  }
}

user_tpl,,,, take the values from the database, transfer them to the template file as parameters, and then parse the template file


<?php
include './sql/pdo.sql.php';
include 'tpl.php';
 $tpl = new tpl\Tpl('./view/', './cache/', 3000);
$link = new pdo_sql();
$dat = ['menu_name', 'menu_url'];
$res = $link->table('blog_menu')->field($dat)->order('id ASC')->select();
$tpl->assign('menu', $res);
$tpl->display('index.html');

More readers interested in PHP can check the topic of this site: PHP Template Technology Summary, PHP Database Operation Skills Summary Based on pdo, PHP Operation and Operator Usage Summary, PHP Network Programming Skills Summary, PHP Basic Syntax Introduction Tutorial, php Object-Oriented Programming Introduction Tutorial, php String (string) Usage Summary, php+mysql Database Operation Introduction Tutorial and php Common Database Operation Skills Summary

I hope this article is helpful to everyone's PHP programming.


Related articles: