国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

PHP實現簡單的模板引擎功能示例

2024-05-04 23:59:58
字體:
來源:轉載
供稿:網友

本文實例講述了PHP實現簡單的模板引擎功能。分享給大家供大家參考,具體如下:

php web開發中廣泛采取mvc的設計模式,controller傳遞給view層的數據,必須通過模板引擎才能解析出來。實現一個簡單的僅僅包含if,foreach標簽,解析$foo變量的模板引擎。

編寫template模板類和compiler編譯類。代碼如下:

<?phpnamespace foo/base;use foo/base/Object;use foo/base/Compiler;/*** */class Template extends Object{  private $_config = [    'suffix' => '.php',//文件后綴名    'templateDir' => '../views/',//模板所在文件夾    'compileDir' => '../runtime/cache/views/',//編譯后存放的目錄    'suffixCompile' => '.php',//編譯后文件后綴    'isReCacheHtml' => false,//是否需要重新編譯成靜態html文件    'isSupportPhp' => true,//是否支持php的語法    'cacheTime' => 0,//緩存時間,單位秒  ];  private $_file;//帶編譯模板文件  private $_valueMap = [];//鍵值對  private $_compiler;//編譯器  public function __construct($compiler, $config = [])  {    $this->_compiler = $compiler;    $this->_config = array_merge($this->_config, $config);  }  /**   * [assign 存儲控制器分配的鍵值]   * @param [type] $values [鍵值對集合]   * @return [type]     [description]   */  public function assign($values)  {    if (is_array($values)) {      $this->_valueMap = $values;    } else {      throw new /Exception('控制器分配給視圖的值必須為數組!');    }    return $this;  }  /**   * [show 展現視圖]   * @param [type] $file [帶編譯緩存的文件]   * @return [type]    [description]   */  public function show($file)  {    $this->_file = $file;    if (!is_file($this->path())) {      throw new /Exception('模板文件'. $file . '不存在!');    }    $compileFile = $this->_config['compileDir'] . md5($file) . $this->_config['suffixCompile'];    $cacheFile = $this->_config['compileDir'] . md5($file) . '.html';    //編譯后文件不存在或者緩存時間已到期,重新編譯,重新生成html靜態緩存    if (!is_file($compileFile) || $this->isRecompile($compileFile)) {      $this->_compiler->compile($this->path(), $compileFile, $this->_valueMap);      $this->_config['isReCacheHtml'] = true;      if ($this->isSupportPhp()) {        extract($this->_valueMap, EXTR_OVERWRITE);//從數組中將變量導入到當前的符號表      }    }    if ($this->isReCacheHtml()) {      ob_start();      ob_clean();      include($compileFile);      file_put_contents($cacheFile, ob_get_contents());      ob_end_flush();    } else {      readfile($cacheFile);    }  }  /**   * [isRecompile 根據緩存時間判斷是否需要重新編譯]   * @param [type] $compileFile [編譯后的文件]   * @return boolean       [description]   */  private function isRecompile($compileFile)  {    return time() - filemtime($compileFile) > $this->_config['cacheTime'];  }  /**   * [isReCacheHtml 是否需要重新緩存靜態html文件]   * @return boolean [description]   */  private function isReCacheHtml()  {    return $this->_config['isReCacheHtml'];  }  /**   * [isSupportPhp 是否支持php語法]   * @return boolean [description]   */  private function isSupportPhp()  {    return $this->_config['isSupportPhp'];  }  /**   * [path 獲得模板文件路徑]   * @return [type] [description]   */  private function path()  {    return $this->_config['templateDir'] . $this->_file . $this->_config['suffix'];  }}
<?phpnamespace foo/base;use foo/base/Object;/*** */class Compiler extends Object{  private $_content;  private $_valueMap = [];  private $_patten = [    '#/{//$([a-zA-Z_/x7f-/xff][a-zA-Z0-9_/x7f-/xff]*)/}#',    '#/{if (.*?)/}#',    '#/{(else if|elseif) (.*?)/}#',    '#/{else/}#',    '#/{foreach //$([a-zA-Z_/x7f-/xff][a-zA-Z0-9_/x7f-/xff]*)}#',    '#/{//(foreach|if)}#',    '#/{//^(k|v)/}#',  ];  private $_translation = [    "<?php echo /$this->_valueMap['//1']; ?>",    '<?php if (//1) {?>',    '<?php } else if (//2) {?>',    '<?php }else {?>',    "<?php foreach (/$this->_valueMap['//1'] as /$k => /$v) {?>",    '<?php }?>',    '<?php echo /$//1?>'  ];  /**   * [compile 編譯模板文件]   * @param [type] $source  [模板文件]   * @param [type] $destFile [編譯后文件]   * @param [type] $values  [鍵值對]   * @return [type]      [description]   */  public function compile($source, $destFile, $values)  {    $this->_content = file_get_contents($source);    $this->_valueMap = $values;    if (strpos($this->_content, '{$') !== false) {      $this->_content = preg_replace($this->_patten, $this->_translation, $this->_content);    }    file_put_contents($destFile, $this->_content);  }}

我們的控制器就可以調用template中的assign方法進行賦值,show方法進行模板編譯了。

/*** [render 渲染模板文件]* @param [type] $file      [待編譯的文件]* @param [type] $values     [鍵值對]* @param array $templateConfig [編譯配置]* @return [type]         [description]*/protected function render($file, $values, $templateConfig = []){    $di = Container::getInstance();    //依賴注入實例化對象    $di->template = function () use ($di, $templateConfig) {      $di->compiler = 'foo/base/Compiler';      $compiler = $di->compiler;      return new /foo/base/Template($compiler, $templateConfig);    };    $di->template->assign($values)->show($file);}

Container類如下:

<?phpnamespace foo/base;use foo/base/Object;class Container extends Object{  private static $_instance;  private $s = [];  public static $instances = [];  public static function getInstance()  {    if (!(self::$_instance instanceof self)) {      self::$_instance = new self();    }    return self::$_instance;  }  private function __construct(){}  private function __clone(){}  public function __set($k, $c)  {    $this->s[$k] = $c;  }  public function __get($k)  {    return $this->build($this->s[$k]);  }  /**   * 自動綁定(Autowiring)自動解析(Automatic Resolution)   *   * @param string $className   * @return object   * @throws Exception   */  public function build($className)  {       // 如果是閉包函數(closures)    if ($className instanceof /Closure) {      // 執行閉包函數      return $className($this);    }    if (isset(self::$instances[$className])) {      return self::$instances[$className];    }    /** @var ReflectionClass $reflector */    $reflector = new /ReflectionClass($className);    // 檢查類是否可實例化, 排除抽象類abstract和對象接口interface    if (!$reflector->isInstantiable()) {      throw new /Exception($reflector . ': 不能實例化該類!');    }    /** @var ReflectionMethod $constructor 獲取類的構造函數 */    $constructor = $reflector->getConstructor();    // 若無構造函數,直接實例化并返回    if (is_null($constructor)) {      return new $className;    }    // 取構造函數參數,通過 ReflectionParameter 數組返回參數列表    $parameters = $constructor->getParameters();    // 遞歸解析構造函數的參數    $dependencies = $this->getDependencies($parameters);    // 創建一個類的新實例,給出的參數將傳遞到類的構造函數。    $obj = $reflector->newInstanceArgs($dependencies);    self::$instances[$className] = $obj;    return $obj;  }  /**   * @param array $parameters   * @return array   * @throws Exception   */  public function getDependencies($parameters)  {    $dependencies = [];    /** @var ReflectionParameter $parameter */    foreach ($parameters as $parameter) {      /** @var ReflectionClass $dependency */      $dependency = $parameter->getClass();      if (is_null($dependency)) {        // 是變量,有默認值則設置默認值        $dependencies[] = $this->resolveNonClass($parameter);      } else {        // 是一個類,遞歸解析        $dependencies[] = $this->build($dependency->name);      }    }    return $dependencies;  }  /**   * @param ReflectionParameter $parameter   * @return mixed   * @throws Exception   */  public function resolveNonClass($parameter)  {    // 有默認值則返回默認值    if ($parameter->isDefaultValueAvailable()) {      return $parameter->getDefaultValue();    }    throw new /Exception('I have no idea what to do here.');  }}

要想以鍵值對的方式訪問對象的屬性必須實現ArrayAccess接口的四個方法,

Object基類代碼如下:

public function offsetExists($offset) {    return array_key_exists($offset, get_object_vars($this));}public function offsetUnset($key) {    if (array_key_exists($key, get_object_vars($this)) ) {      unset($this->{$key});    }}public function offsetSet($offset, $value) {    $this->{$offset} = $value;}public function offsetGet($var) {    return $this->$var;}

在某一控制器中就可以調用父類Controller的render方法啦

復制代碼 代碼如下:
$this->render('test/index', ['name' => 'tom', 'age' => 20, 'friends' => ['jack', 'rose']], ['cacheTime' => 10]);

 

編寫視圖模板文件'test/index':

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Document</title></head><body>  <p>展示模板文件視圖</p>   <p>{$name}</p>  <p>{$age}</p>  <?php echo ++$age;?>  {if $age > 18}    <p>已成年</p>  {else if $age < 10}    <p>小毛孩</p>  {/if}  {foreach $friends}    <p>{^v} </p>  {/foreach}</body></html>

至此,一個簡單的模板編譯引擎就寫好了。

希望本文所述對大家基于smarty模板的PHP程序設計有所幫助。


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 饶河县| 罗定市| 安宁市| 安达市| 尚义县| 雅安市| 海伦市| 南木林县| 水城县| 喀喇沁旗| 阿鲁科尔沁旗| 隆化县| 平乡县| 洛川县| 二手房| 抚松县| 格尔木市| 昌黎县| 万盛区| 绍兴县| 夏邑县| 徐水县| 温州市| 腾冲县| 库伦旗| 资源县| 区。| 沂源县| 措勤县| 涡阳县| 宁安市| 青州市| 长宁区| 武山县| 台东市| 耒阳市| 乌兰县| 榆树市| 新巴尔虎右旗| 六盘水市| 印江|