tp5源码分析之视图
视图(View),作为(MVC)的一员,代表对输出数据的Web界面组织操作对象。
视图可以用来存储模板变量
最终调用模板引擎 将(模板变量) 与 (模板文件)解析为输出的Web界面
View::instance()
单例模式,创建全局唯一的视图对象
public static function instance($engine = [], $replace = [])
{
if (is_null(self::$instance)) {
self::$instance = new self($engine, $replace);
}
return self::$instance;
}
$view->__construct()
视图构造函数,创建视图对象
public function __construct($engine = [], $replace = [])
{
// 初始化模板引擎
$this->engine((array) $engine);
$this->replace = $replace;
}
$view->engine()
模板引擎创建,根据配置创建相应的模板引擎(默认为Think)
public function engine($options = [])
{
if (is_string($options)) {
$type = $options;
$options = [];
} else {
$type = !empty($options["type"]) ? $options["type"] : "Think";
}
$class = false !== strpos($type, "\") ? $type : "\think\view\driver\" . ucfirst($type);
if (isset($options["type"])) {
unset($options["type"]);
}
$this->engine = new $class($options);
return $this;
}
由上可知,默认的模板引擎(Think)实现为viewdriverThink.php文件。模板引擎具体的信息见 模板引擎 章节
$view->config()
模板引擎配置,配置模板引擎参数
public function config($name, $value = null)
{
$this->engine->config($name, $value);
return $this;
}
2-1 模板变量
$view->assign()
存储数据到模板变量中。
public function assign($name, $value = "")
{
if (is_array($name)) {
$this->data = array_merge($this->data, $name);
} else {
$this->data[$name] = $value;
}
return $this;
}
$view->__get()
模板变量获取快捷操作
public function __get($name)
{
return $this->data[$name];
}
$view->__set()
模板变量赋值快捷操作
public function __set($name, $value)
{
$this->data[$name] = $value;
}
$view->__isset()
模板变量检测快捷操作
public function __isset($name)
{
return isset($this->data[$name]);
}
2-2 模板文件
模板文件,作为界面组织的文件。模板引擎将模板变量填充到模板文件中生成输出的Web页面
$view->replace()
模板字符串替换内容配置
public function replace($content, $replace = "")
{
if (is_array($content)) {
$this->replace = array_merge($this->replace, $content);
} else {
$this->replace[$content] = $replace;
}
return $this;
}
$view->fetch()
获取模板文件解析结果
public function fetch($template = "", $vars = [], $replace = [], $config = [], $renderContent = false)
{
// 模板变量
$vars = array_merge($this->data, $vars);
// 页面缓存
ob_start();
ob_implicit_flush(0);
// 渲染输出
$method = $renderContent ? "display" : "fetch";
$this->engine->$method($template, $vars, $config);
// 获取并清空缓存
$content = ob_get_clean();
// 内容过滤标签
Hook::listen("view_filter", $content);
// 允许用户自定义模板的字符串替换
$replace = array_merge($this->replace, $replace);
if (!empty($replace)) {
$content = strtr($content, $replace);
}
return $content;
}
$view->display()
输出模板文件解析结果
public function display($content, $vars = [], $replace = [], $config = [])
{
return $this->fetch($content, $vars, $replace, $config, true);
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: tf.split (API r1.3)
- 下一篇: url中特殊符号转义