Рубрики
Uncategorized

Принципы, определения и примеры использования движка шаблонов PHP

Автор оригинала: David Wong.

В этой статье представлен принцип, определение и использование движка шаблонов PHP . Чтобы поделиться с вами для вашей справки, следующим образом:

Хранилище шаблонов исходный файл шаблона

Класс инструментов для компиляции шаблонов

Compline.class. php

template = $template;
   $this->comfile = $compileFile;
   $this->content = file_get_contents($template);
   if($config['php_turn'] === false)
   {
     $this->T_P[] = "/<\?(=|php|)(.+?)\?>/is";
     $this->T_R[] = "T_P[] = "/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/";
   //{foreach $B} or {loop $B}
   $this->T_P[] = "/\{(loop|foreach) \$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/i";
   //{[K|V]}
   $this->T_P[] = "/\{([K|V])\}/";
   //{/ foreach} or {\ loop} or {\ if}
   $this->T_P[] = "/\{\/(loop|foreach|if)}/i";
   //{if (condition)}
   $this->T_P[] = "/\{if (.* ?)\}/i";
   //{(else if | elseif)}
   $this->T_P[] = "/\{(else if|elseif) (.* ?)\}/i";
   //{else}
   $this->T_P[] = "/\{else\}/i";
   //{Chen... Chen or *... Chen, comment}
   $this->T_P[] = "/\{(\#|\*)(.* ?)(\#|\*)\}/";
   $this->T_R[] = "value['\1']; ?>";
   $this->T_R[] = "value['\2'] as $K => $V) { ?>";
   $this->T_R[] = "";
   $this->T_R[] = "";
   $this->T_R[] = "";
   $this->T_R[] = "";
   $this->T_R[] = "";
   $this->T_R[] = "";
  }
  public function compile()
  {
   $this->c_all();
   $this->c_staticFile();
   file_put_contents($this->comfile, $this->content);
  }
  public function c_all()
  {
   $this->content = preg_replace($this->T_P, $this->T_R, $this->content);
  }
  /**
  *Add parsing of JavaScript files
  * @return [type] [description]
  */
  public function c_staticFile()
  {
   $this->content = preg_replace('/\{\!(.* ?)\!\}/', '', $this->content);
  }
  public function __set($name, $value)
  {
   $this->$name = $value;
  }
  public function __get($name)
  {
   if(isset($this->$name))
   {
     return $this->$name;
   }
   else
   {
     return null;
   }
  }
}

Compline.class. php

 '. TPL', // suffix of template
   'templatedir' = > 'template /', // the folder where the template is located
   'compiledir' = > cache / ', // directory stored after compilation
   'cache_html' = > true, // whether to compile to a static HTML file
   'suffix_cache' = > '. HTML', // set the suffix of the compiled file
   'cache_time' = > 7200, // set how long to update automatically
   'php_turn' = > true, // set whether PHP native code is supported
   'debug'     => false,
   );
  Public $file; // template file name, without path
  Public $debug = array(); // debugging information
  Private $value = array(); // value stack
  Private $compiletool; // compiler
  private $controlData = array();
  Static private $instance = null; // template class object
  public function __construct($arrayConfig = array())
  {
   $this->debug['begin'] = microtime(true);
   $this->arrayConfig = array_merge($this->arrayConfig, $arrayConfig);
   $this->getPath();
   if(!is_dir($this->arrayConfig['templateDir']))
   {
     exit("template dir isn't found!");
   }
   if(!is_dir($this->arrayConfig['compileDir']))
   {
     if(strtoupper(substr(PHP_OS,0,3)) === 'WIN')
     {
      mkdir($this->arrayConfig['compileDir']);
     }
     else
     {
      mkdir($this->arrayConfig['compileDir'], 0770, true);
     }
   }
   include('Compile.class.php');
  }
  public function getPath()
  {
   $this->arrayConfig['templateDir'] = strstr(realpath($this->arrayConfig['templateDir']), '\', '/').'/';
   $this->arrayConfig['compileDir'] = strstr(realpath($this->arrayConfig['compileDir'])), '\', '/').'/';
  }
  /**
  *Get an instance of the template engine
  */
  public static function getInstance()
  {
   if(is_null(self::$instance))
   {
     self::$instance = new Template();
   }
   return self::$instance;
  }
  /**
  *Set engine parameters separately
  *It also supports setting multiple parameters at one time
  */
  public function setConfig($key, $value = null)
  {
   if(is_array($key))
   {
     $this->arrayConfig = $key + $this->arrayConfig;
   }
   else
   {
     $this->arrayConfig[$key] = $value;
   }
  }
  /**
  *Get the current template engine configuration for debugging purposes only
  */
  public function getConfig($key = null)
  {
   if($key && array_key_exists($key, $this->arrayConfig))
   {
     return $this->arrayConfig[$key];
   }
   else
   {
     return $this->arrayConfig;
   }
  }
  /**
  *Inject a single variable
  */
  public function assign($key, $value)
  {
   $this->value[$key] = $value;
  }
  /**
  *Inject array variable
  */
  public function assignArray($array)
  {
   if(is_array($array))
   {
     foreach ($array as $k => $v) {
      $this->value[$k] = $v;
     }
   }
  }
  /**
  *Get the location of the template
  * @return [type] [description]
  */
  public function path()
  {
   return $this->arrayConfig['templateDir'].$this->file.$this->arrayConfig['suffix'];
  }
  /**
  *Determine whether the configuration file requires caching
  */
  public function needCache()
  {
   return $this->arrayConfig['cache_html'];
  }
  /**
  *Determine whether cache is needed
  */
  public function reCache($file)
  {
   $flag = false;
   $cacheFile = $this->arrayConfig['compileDir'].md5($file).$this->arrayConfig['suffix_cache'];
   if($this->arrayConfig['cache_html'] === true)
   {
     //Cache required
     $timeFlag = (time() - @filemtime($cacheFile)) < $this->arrayConfig['cache_time'] ? true : false;
     if(is_file($cacheFile) && filesize($cacheFile) > 1 && $timeFlag)
     {
      //Cache exists and does not expire
      $flag = true;
     }
     else
     {
      $flag = false;
     }
   }
   return $flag;
  }
  /**
  *Presentation template
  */
  public function show($file)
  {
   $this->file = $file;
   if(!is_file($this->path()))
   {
     Exit ('No corresponding template found ');
   }
   $compileFile = $this->arrayConfig['compileDir'].md5($file).'.php';
   $cacheFile = $this->arrayConfig['compileDir'].md5($file).$this->arrayConfig['suffix_cache'];
   if($this->reCache($file) === false)
   {
     //If caching is required
     $this->debug['cached'] = 'false';
     $this->compileTool = new Compile($this->path(), $compileFile, $this->arrayConfig);
     if($this->needCache())
     {
      ob_start();
     }
     extract($this->value, EXTR_OVERWRITE);
     if(!is_file($compileFile) || fileatime($compileFile) < filemtime($this->path()))
     {
      $this->compileTool->value = $this->value;
      $this->compileTool->compile();
      include $compileFile;
     }
     else
     {
      include $compileFile;
     }
     if($this->needCache())
     {
      $message = ob_get_contents();
      file_put_contents($cacheFile, $message);
     }
   }
   else
   {
     readfile($cacheFile);
     $this->debug['cached'] = 'true';
   }
   $this->debug['spend'] = microtime(true) - $this->debug['begin'];
   $this->debug['count'] = count($this->value);
   $this->debug_info();
  }
  public function debug_info()
  {
   if($this->arrayConfig['debug'] === true)
   {
     echo "
", '-------------------- debug_info--------------', "
"; Echo 'program running date:', date ("y-m-d H: I: s"), "< br / >; Echo 'template parsing time:' $this - > debug ['spend '],' seconds', "< br / >; Echo 'template contains the number of tags:', $this - > debug ['Count '], "< br / >; Echo 'use static cache:' $this - > debug ['cached '], "< br / >; Echo 'template engine instance parameter:', var_dump ($this - > getconfig()); } } /** *Clear cached HTML files * @return [type] [description] */ public function clean() { if($path === null) { $path = $this->arrayConfig['compileDir']; $path = glob($path.'* '.$this->arrayConfig['suffix_cache']); } else { $path = $this->arrayConfig['compileDir'].md5($path).$this->arrayConfig['suffix_cache']; } foreach ((array)$path as $v) { unlink($v); } } }

Compline.class. php

 true));
$tpl->assign('data', 'hello world');
$tpl->assign('person', 'htGod');
$tpl->assign('data1', 3);
$arr = array(1,2,3,4,'5',6);
$tpl->assign('b', $arr);
$tpl->show('member');

Для получения дополнительной информации о PHP, пожалуйста, ознакомьтесь со следующими разделами: Краткое описание технологии шаблонов PHP, краткое описание навыков работы с базами данных на основе PHP PDO, краткое описание операций с PHP и использования операторов, краткое описание навыков сетевого программирования PHP, учебник по основному синтаксису PHP, учебник по объектно-ориентированному программированию PHP, Краткое описание использования строк PHP , учебник по работе с базами данных PHP + MySQL и краткое описание общих навыков работы с базами данных PHP

Я надеюсь, что эта статья будет полезна для программирования на PHP.