欢迎光临
我们一直在努力

thinkPHP框架简单处理模板类的方法及步骤

<?php
// ============================================================================
class template
{
	public $v        = array(); // 变量
	public $html_dir = '';      // html文件夹
	public $temp_dir = 'temp/'; // 生成的PHP文件存放目录
	public $tags     = array(); // 待处理的标签数组
	public $tags_rp  = array(); // 标签替换数组
	public $html_con = '';      // html文件内容
	public $suffix   = 'php';   // php文件后缀

	// 显示模板
	function display($file='')
	{
		$html_file = $this->html_dir . $file . '.html';

		if (!is_file($html_file)) exit('模板文件不存在!' . $file);

		// 相应的PHP文件
		$php_file = "{$this->temp_dir}$file.{$this->suffix}";

		// php文件已存在
		if (is_file($php_file))
		{
			$mtime_h = filemtime($html_file); // HTML文件修改时间
			$mtime_p = filemtime($php_file);  // PHP文件修改时间

			// HTML文件修改时间不大于PHP文件修改时间  HTML没有修改
			if ($mtime_p && $mtime_h <= $mtime_p)
			{
				include $php_file;
				return;
			}
		}

		// 加载html文件内容
		$this->html_con = file_get_contents($html_file);

		// 加载直接可替换标签数组
		$this->set_tags_rp();

		// 加载待处理内容数组
		$this->get_tag();

		// 格式化待处理标签
		$this->format_tag();

		// 生成的PHP文件
		$this->_fwrite($php_file, $this->html_con);

		// 包含文件
		include $php_file;
	}

	// 加载待处理内容数组
	function get_tag()
	{
		$tags_rp_keys   = array_keys($this->tags_rp);

		$this->html_con = str_replace($tags_rp_keys, $this->tags_rp, $this->html_con);

		preg_match_all('/{[\$\w]+.*}/U', $this->html_con, $this->tags);

		$this->tags     = $this->tags[0];
	}

	// 格式化待处理标签   可以此处自定义函数处理方法
	function format_tag()
	{
		if (!$this->tags) return;

		$tags_key = array();
		$tags_val = array();

		foreach ($this->tags as $v)
		{
			$tags_key[] = $v;

			// 变量  例 {$data.i.$sort.id}  /  {$data.i.$sort.id.$name}  /  {$data.i.$sort.id.$name|gdate,1,2} gdate 为函数 1,2对应参数 支持多级函数 如 {$data.title|gstr,1|gdate,2}
			if (substr($v, 0, 2) == '{
)
			{
				$variable   = str_replace(array('{', '}'), '', $v);
				$variable   = explode('|', $variable);
				$variable   = $variable[1] ? $this->function_variable($variable) : $this->format_variable($variable[0]);
				$tags_val[] = "<?php echo " . $variable . ";?>";
				continue;
			}

			// if语句  例 {if $i>0}{/if}
			if (substr($v, 0, 4) == '{if ')
			{
				$variable   = str_replace(array('{if ', '}'), '', $v);
				$tags_val[] = "<?php if (" . $this->format_variable($variable) . ") {?>";
				continue;
			}

			// php原生代码  例 {php echo '';} 代码中不能含有{}
			if (substr($v, 0, 5) == '{php ')
			{
				$variable   = str_replace(array('{php ', '}'), '', $v);
				$tags_val[] = "<?php " . $this->format_variable($variable) . ";?>";
				continue;
			}

			// 常量  {const app_path} 不区分大小写  强转大写
			if (substr($v, 0, 7) == '{const ')
			{
				$variable   = str_replace(array('{const ', '}'), '', $v);
				$tags_val[] = "<?php echo " . strtoupper($variable) . ";?>";
				continue;
			}

			// cookie  {cookie key}
			if (substr($v, 0, 8) == '{cookie ')
			{
				$variable   = str_replace(array('{cookie ', '}'), '', $v);
				$tags_val[] = '<?php echo $_COOKIE[\'' . $this->format_variable($variable) . '\'];?>';
				continue;
			}

			// session  {session key}
			if (substr($v, 0, 9) == '{session ')
			{
				$variable   = str_replace(array('{session ', '}'), '', $v);
				$tags_val[] = '<?php echo $_SESSION[\'' . $this->format_variable($variable) . '\'];?>';
				continue;
			}

			// elseif语句  例 {if $i>0}{elseif $i>1}{/if}
			if (substr($v, 0, 8) == '{elseif ')
			{
				$variable   = str_replace(array('{elseif ', '}'), '', $v);
				$tags_val[] = "<?php } elseif (" . $this->format_variable($variable) . ") {?>";
				continue;
			}

			// foreach语句 数组循环  例 {foreach from=data item=v key=k} / {foreach from=data val=v key=k}
			if (substr($v, 0, 9) == '{foreach ')
			{
				$variable   = $this->format_variable(str_replace(array('{foreach ', '}'), '', $v));
				$variable   = explode(' ', trim($variable));

				$tags_val_c = array();

				foreach ($variable as $val)
				{
					if ($val == '') continue;
					$val = explode('=', $val);

					if (strpos($val[1], '
) === false) $val[1] = $this->set_variable($val[1]);
					switch ($val[0])
					{
						case 'data':
							$tags_val_c[0] = '<?php if (' . $val[1] . ') foreach (' . $val[1] . ' as ';
							break;
						case 'key':
							$tags_val_c[1] = $val[1] . ' => ';
							break;
						case 'item': // 同val
							$tags_val_c[2] = $val[1];
							break;
						case 'val': // 同item
							$tags_val_c[2] = $val[1];
							break;
						default:
					}

					ksort($tags_val_c);
				}

				$tags_val[] = implode('', $tags_val_c) . '){?>';
				continue;
			}

			// include包含文件  例 {include $file/index.html}  /  {include index.html}
			if (substr($v, 0, 9) == '{include ')
			{
				$variable   = trim(str_replace(array('{include ', '}'), '', $v));
				$variable   = $variable{0}=='

							? $this->format_variable($variable, 1) // 包含变量
							: $variable;

				$tags_val[] = '<?php $this->display(\'' . $variable . '\');?>';
				continue;
			}

			// for语句  例 {for $i=0; $i<2; $i++}  /  {for beg=0 end=2 }  / {for beg=0 end=2 key=i}
			if (substr($v, 0, 5) == '{for ')
			{
				$variable   = $this->format_variable(str_replace(array('{for ', '}'), '', $v));
				$tags_val_c = array();

				// 自定义增长变量   例 {for $i=0; $i<2; $i++}
				if (strpos($v, '
) !== false)
				{
					$tags_val[] = "<?php for ($variable) {?>";
					continue;
				}

				$variable   = explode(' ', trim($variable));

				// 例 {for beg=0 end=2 }  / {for beg=0 end=2 key=i}
				foreach ($variable as $val)
				{
					if ($val=='') continue;
					$val = explode('=', $val);

					$tags_val_c[0] = '<?php for (';
					$key           = 'i';

					switch ($val[0])
					{
						case 'key':
							$key           = $val[1];
							break;
						case 'beg':
							$tags_val_c[2] = $val[1] . '; ';
							break;
						case 'end':
							$tags_val_c[3] = "\$this->v['$key']<$val[1]; ";
							break;
						default:
					}

					$tags_val_c[1] = "\$this->v['$key']=";

					ksort($tags_val_c);
				}

				$tags_val[] = implode('', $tags_val_c) . "\$this->v['$key']++) {?>";
				continue;
			}

			// select标签  例 {select dfsel=1 dfval=请选择 data=data fkey=key fval=val skey=name sval=code}
			// dfsel 默认选择项   dfval 第一选择项内容   data 要展示的数组
			// fkey 数组foreach的键名 fval 数组foreach的值名  skey 如果fval是多级数组为显示的键名  sval 如果sval则option的value=sval相关值
			// 其他自定义属性原样显示
			if (substr($v, 0, 8) == '{select ')
			{
				$variable   = str_replace(array('{select ', '}'), '', $v);

				$tags_val_c = '';
				$tags_val_o = ''; // 下拉列表 option
				$tags_vals  = array();

				// 处理属性参数
				$variable   = explode(' ', trim($variable));
				$ex         = array('dfsel', 'dfval', 'data', 'fkey', 'fval', 'skey', 'sval');
				$style      = array();
				foreach ($variable as $val)
				{
					if ($val == '') continue;

					$val = explode('=', $val);

					if (!in_array($val[0], $ex))
					{
						$style[] = implode('=', $val);
						continue;
					}

					$tags_vals[$val[0]] = str_replace(array('"', '\''), '', $val[1]);
					if ($val[0] == 'data') $tags_vals[$val[0]] = $this->set_variable(str_replace('
, '', $val[1]));
					if ($val[0] == 'dfsel') $tags_vals[$val[0]] = $this->set_variable(str_replace('
, '', $val[1]));
				}

				// 属性默认值
				if (!isset($tags_vals['dfsel'])) $tags_vals['dfsel'] = '\'\'';
				if (!$tags_vals['dfval']) $tags_vals['dfval'] = '请选择';
				if (!$tags_vals['fval'])  $tags_vals['fval']  = 'v';
				if (!$tags_vals['fkey'])  $tags_vals['fkey']  = 'k';
				if ( $tags_vals['skey'])  $tags_vals['skey']  = "['$tags_vals[skey]']";

				$k = '$this->v[\'' . $tags_vals['fkey'] . '\']';
				$v = '$this->v[\'' . $tags_vals['fval'] . '\']';

				$ov= $tags_vals['sval'] ? ('$this->v[\'' . $tags_vals['fval'] . '\'][\'' . $tags_vals['sval'] . '\']') : $k;

				// option 内容
				$tags_val_o = '<?php if (' . $tags_vals['data'] . ') foreach (' . $tags_vals['data'] . ' as ' . $k . ' => ' . $v . ') {?>
							<option value="<?php echo ' . $ov . ';?>"<?php if (' . $k . ' == ' . $tags_vals['dfsel'] . ') echo \' selected\';?>><?php echo ' . $v . $tags_vals['skey'] . ';?></option>
							<?php }?>';

				$style = implode($style, ' ');

				$tags_val_c = "<select $style>
					<option value=\"\">$tags_vals[dfval]</option>
					$tags_val_o
					</select>";

				$tags_val[] = $tags_val_c;
				continue;
			}

			// url方法
			if (substr($v, 0, 5) == '{url ')
			{
				$variable   = trim(str_replace(array('{url ', '}'), '', $v));
				$tags_val[] = strpos($variable, '
) !== false
							? '<?php echo url(\'' . $this->format_variable($variable, 1) . '\');?>' // 包含变量
							: '<?php echo url(\'' . $variable . '\');?>';
				continue;
			}

			// admin方法
			if (substr($v, 0, 7) == '{admin ')
			{
				$variable   = trim(str_replace(array('{admin ', '}'), '', $v));
				$tags_val[] = strpos($variable, '
) !== false
							? '<?php echo admin(\'' . $this->format_variable($variable, 1) . '\');?>' // 包含变量
							: '<?php echo admin(\'' . $variable . '\');?>';
				continue;
			}

			$tags_val[] = $v;
		}

		$this->html_con = str_replace($tags_key, $tags_val, $this->html_con);
	}

	// 格式化变量    connection 返回连接式字符串
	function format_variable($str='', $connection=0)
	{
		if ($str == '') return '';

		$str = trim($str);

		preg_match_all('/\$\w+[\.\w\$]*/i', $str, $variables);

		$variables = $variables[0];

		if (!$variables) return $str;

		$temp = array();
		foreach ($variables as $variable)
		{
			// 单重 如$test.v
			if (strpos($variable, '.
) === false)
			{
				$temp[$variable] = $connection
					? '\' . ' . $this->set_variable(str_replace('
, '', $variable)) . ' . \''
					: $this->set_variable(str_replace('
, '', $variable));
				continue;
			}

			// 多重 如$test.$v.1
			$childs = explode('.
, $variable);

			$t[]    = array_shift($childs);
			$t[0]   = $this->set_variable(str_replace('
, '', $t[0]));
			foreach ($childs AS $key => $val) $t[] = '['. $this->set_variable($val) . ']';
			$temp[$variable] = $connection
				? '\' . ' . implode('', $t) . ' . \''
				: implode('', $t);
		}

		$kyes = array_keys($temp);
		return str_replace($kyes, $temp, $str);
	}

	// 处理变量
	function set_variable($variable='')
	{
		if ($variable == '') return '';

		// 处理{$test.id.$data.time.$name} => $this->v['test']['id'][$this->v['data']['time']]['name'] 复杂数组
		if (strrpos($variable, '
) !== false)
		{
			$variable = str_replace('
, '', $variable);
			$str = '\'' . $variable . '\'';
			return $str;
		}

		// 单层数组
		if (strrpos($variable, '.') === false) return '$this->v[\'' . $variable . '\']';

		// 多层数组
		$t   = explode('.', $variable);
		foreach ($t as $k=>$v) if ( $v=='' ) unset($t[$k]);
		$_var_name = array_shift($t);

		$str = '$this->v[\'' . $_var_name . '\']';

		foreach ($t as $val) $str .= '[\'' . $val . '\']';

		return $str;
	}

	// 处理变量函数 支持多级函数 如 {$data.title|gstr,1|gdate,2}
	function function_variable($vf='')
	{
		if ($vf[1] == '') return $this->format_variable($vf[0]);

		$variable  = array_shift($vf);
		$variable  = $this->format_variable($variable);

		if ($vf) foreach ($vf as $v)
		{
			$fns  = explode(',', $v);
			$fn  = array_shift($fns);
			if ($fns) $fnc = ', \'' . implode('\', \'', $fns) . '\'';
			$variable = "$fn(" . $variable . "$fnc)";
		}

		return $variable;
	}

	// 注册变量
	function assign($tpl_var, $value = '')
	{
		if (!is_array($tpl_var))
		{
			$this->v[$tpl_var] = $value;
			return;
		}

		foreach ($tpl_var as $key => $val) if ($key != '') $this->v[$key] = $val;
	}

	// 加载直接可替换标签数组
	function set_tags_rp()
	{
		$this->tags_rp   = array
		(
			'{/if}'      => '<?php }?>',
			'{else}'     => '<?php } else {?>',
			'{/for}'     => '<?php }?>',
			'{/foreach}' => '<?php }?>',
		);
	}

	// 写文件 file 绝对路径 content 文件内容
	function _fwrite($file='', $content='')
	{
		if (empty($file)) return;

		$this->mk_dir(dirname($file));
		file_put_contents($file, $content);
	}

	// 检测文件夹,创建 dir 文件夹名
	function mk_dir($dir='')
	{
		if ($dir == '') return;

		if (file_exists($dir)) return;

		$dir   = str_replace('\\', '/', $dir);
		$dir   = explode('/', $dir);//转换成数组
		$count = count($dir);
		$d     = '';

		if ($dir) foreach ($dir as $v)
		{
			if (!$v) continue;

			$d .= $v . '/';
			if (!file_exists($d))
			{
				mkdir($d, 0777, true);
				$this->_fwrite($d . 'index.html');
			}
		}
	}
}
赞(0) 打赏
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 ivillcn@qq.com 举报,一经查实,本站将立刻删除。
文章名称:《thinkPHP框架简单处理模板类的方法及步骤》
文章链接:https://www.bilibiji.com/article/163.html

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

微信扫一扫

登录

找回密码

注册