View类
来源:互联网 发布:域名跟空间怎么绑定 编辑:程序博客网 时间:2024/05/21 15:59
View继承了component,用于渲染视图文件
yii2\base\View.php
<?php/** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */namespace yii\base;use Yii;use yii\helpers\FileHelper;use yii\widgets\Block;use yii\widgets\ContentDecorator;use yii\widgets\FragmentCache;/** * View represents a view object in the MVC pattern. * MVC中的视图 * View provides a set of methods (e.g. [[render()]]) for rendering purpose. * 视图提供了一套渲染页面的方法 * @property string|boolean $viewFile The view file currently being rendered. False if no view file is being * rendered. This property is read-only. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */class View extends Component{ /** * @event Event an event that is triggered by [[beginPage()]]. * 事件被[beginPage()]触发 */ const EVENT_BEGIN_PAGE = 'beginPage'; /** * @event Event an event that is triggered by [[endPage()]]. * 事件被[endPage()]触发 */ const EVENT_END_PAGE = 'endPage'; /** * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file. * 事件被[renderFile()]触发前呈现一个视图文件 */ const EVENT_BEFORE_RENDER = 'beforeRender'; /** * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file. * 事件被[renderFile()]触发后呈现一个视图文件 */ const EVENT_AFTER_RENDER = 'afterRender'; /** * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked. * ViewContextInterface背景下 [renderFile()]方法被调用 */ public $context; /** * @var mixed custom parameters that are shared among view templates. * 视图模板中共享的自定义参数 */ public $params = []; /** * @var array a list of available renderers indexed by their corresponding supported file extensions. * Each renderer may be a view renderer object or the configuration for creating the renderer object. * 一个可用的渲染索引列表。每个渲染器是一个渲染器对象或创建渲染对象配置数组 * For example, the following configuration enables both Smarty and Twig view renderers: * * ~~~ * [ * 'tpl' => ['class' => 'yii\smarty\ViewRenderer'], * 'twig' => ['class' => 'yii\twig\ViewRenderer'], * ] * ~~~ * * If no renderer is available for the given view file, the view file will be treated as a normal PHP * and rendered via [[renderPhpFile()]]. */ public $renderers; /** * @var string the default view file extension. This will be appended to view file names if they don't have file extensions. * 默认视图文件扩展名,文件没有扩展名的情况下自动加载 */ public $defaultExtension = 'php'; /** * @var Theme|array|string the theme object or the configuration for creating the theme object. * If not set, it means theming is not enabled.主题对象或创建主题对象的配置 未设置则不启用 */ public $theme; /** * @var array a list of named output blocks. The keys are the block names and the values * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]] * to capture small fragments of a view. They can be later accessed somewhere else * through this property. * 一个输出块列表。键是块名称值为内容。可以调用 [beginblock()]和[endblock()]捕获视图的小片段 * 可以在其他地方通过这个属性访问。 */ public $blocks; /** * @var array a list of currently active fragment cache widgets. This property * is used internally to implement the content caching feature. Do not modify it directly. * 当前操作片段的缓存部件列表。用于内部实现内容缓存功能。不要直接修改 * @internal */ public $cacheStack = []; /** * @var array a list of placeholders for embedding dynamic contents. This property * is used internally to implement the content caching feature. Do not modify it directly. * 嵌入动态内容占位符列表。 用于内部实现内容缓存功能。不要直接修改 * @internal */ public $dynamicPlaceholders = []; /** * @var array the view files currently being rendered. There may be multiple view files being * rendered at a moment because one view may be rendered within another. * 正在渲染的视图文件。可能有多个视图文件被渲染,因为一个视图可以在另一个视图中呈现 */ private $_viewFiles = []; /** * Initializes the view component.初始化视图组件 */ public function init() { parent::init(); //调用父类的方法 if (is_array($this->theme)) { if (!isset($this->theme['class'])) { $this->theme['class'] = 'yii\base\Theme';//是数组,没有设置类名,则类名'yii\base\Theme' } $this->theme = Yii::createObject($this->theme);//设置了类名,调用配置创建对象 } elseif (is_string($this->theme)) {//以字符串参数的形式创建对象 $this->theme = Yii::createObject($this->theme); } } /** * Renders a view. * 渲染一个视图 * The view to be rendered can be specified in one of the following formats: * * - path alias (e.g. "@app/views/site/index"); * 路径别名 * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application. * 绝对路径,会在[Application::viewPath|view path]下查找文件 * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. * The actual view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]]. * 模块下的绝对路径,会在[Module::viewPath|view path]下查找文件 * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be * looked for under the [[ViewContextInterface::getViewPath()|view path]] of the view `$context`. * 相对路径,会在[ViewContextInterface::getViewPath()|view path]下查找文件 * If `$context` is not given, it will be looked for under the directory containing the view currently * being rendered (i.e., this happens when rendering a view within another view). * * @param string $view the view name. 视图名称 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. * 视图中应用参数 * @param object $context the context to be assigned to the view and can later be accessed via [[context]] * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate * the view file corresponding to a relative view name. 对应情景 * @return string the rendering result * @throws InvalidParamException if the view cannot be resolved or the view file does not exist. * @see renderFile() */ public function render($view, $params = [], $context = null) { $viewFile = $this->findViewFile($view, $context);//查找视图文件路径 return $this->renderFile($viewFile, $params, $context);//渲染视图文件 } /** * Finds the view file based on the given view name.通过视图文件名查找视图文件 * @param string $view the view name or the path alias of the view file. Please refer to [[render()]] * on how to specify this parameter. 视图名称或路径视图文件的别名 * @param object $context the context to be assigned to the view and can later be accessed via [[context]] * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate * the view file corresponding to a relative view name. 对应情景 * @return string the view file path. Note that the file may not exist. 文件路径 * @throws InvalidCallException if a relative view name is given while there is no active context to * determine the corresponding view file. */ protected function findViewFile($view, $context = null) { if (strncmp($view, '@', 1) === 0) { // e.g. "@app/views/main" 判断是否是别名路径,是则获取真实路径 $file = Yii::getAlias($view); } elseif (strncmp($view, '//', 2) === 0) { // e.g. "//layouts/main" 以//开始,查找文件路径,拼接视图文件路径 $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } elseif (strncmp($view, '/', 1) === 0) { // e.g. "/site/index" if (Yii::$app->controller !== null) { //以/开始,且控制器存在,查找控制器对应的文件目录,拼接路径 $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/'); } else { throw new InvalidCallException("Unable to locate view file for view '$view': no active controller."); } } elseif ($context instanceof ViewContextInterface) { //对应情景存在 查找文件路径,拼接视图文件路径 $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view; } elseif (($currentViewFile = $this->getViewFile()) !== false) { //当前渲染文件存在,拼接路径 $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view; } else { throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context."); } if (pathinfo($file, PATHINFO_EXTENSION) !== '') { return $file;//视图文件的扩展名不为空,返回扩展名 } $path = $file . '.' . $this->defaultExtension; //给视图文件添加扩展名 if ($this->defaultExtension !== 'php' && !is_file($path)) { $path = $file . '.php'; } return $path;//返回路径 } /** * Renders a view file. * 渲染一个视图文件。 * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long * as it is available. * 如果[theme]可用,将渲染视图文件的主题版本直到[theme]不可用 * The method will call [[FileHelper::localize()]] to localize the view file. * 调用[FileHelper::localize()]方法本地化视图文件 * If [[renderers|renderer]] is enabled (not null), the method will use it to render the view file. * Otherwise, it will simply include the view file as a normal PHP file, capture its output and * return it as a string. * 如果[[renderers|renderer]]启用,该方法将用它来渲染视图文件。否则,将视图文件作为一个正常的PHP文件包含进来,获取其输出并返回一个字符串。 * @param string $viewFile the view file. This can be either an absolute file path or an alias of it. * 视图文件。可以是绝对路径或它的别名。 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. * 视图文件执行的参数 * @param object $context the context that the view should use for rendering the view. If null, * existing [[context]] will be used. * 用于渲染视图的上下文 * @return string the rendering result * @throws InvalidParamException if the view file does not exist */ public function renderFile($viewFile, $params = [], $context = null) { $viewFile = Yii::getAlias($viewFile);//处理输入的视图文件名 if ($this->theme !== null) { $viewFile = $this->theme->applyTo($viewFile);//如果theme非空,应用到视图文件 } if (is_file($viewFile)) { $viewFile = FileHelper::localize($viewFile);//本地化视图文件 } else { throw new InvalidParamException("The view file does not exist: $viewFile"); } $oldContext = $this->context; if ($context !== null) { $this->context = $context; } $output = ''; $this->_viewFiles[] = $viewFile;//记录当前渲染文件 if ($this->beforeRender($viewFile, $params)) {//如果前置事件执行成功 Yii::trace("Rendering view file: $viewFile", __METHOD__);//记录trace信息 $ext = pathinfo($viewFile, PATHINFO_EXTENSION);//视图文件扩展名 if (isset($this->renderers[$ext])) {//视图文件的扩展名是否支持 if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) { $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]); } /* @var $renderer ViewRenderer */ $renderer = $this->renderers[$ext];//赋值view渲染器对象 $output = $renderer->render($this, $viewFile, $params);//渲染视图文件 } else {//视图文件不是支持的类型,以普通php文件处理 $output = $this->renderPhpFile($viewFile, $params); } $this->afterRender($viewFile, $params, $output); } array_pop($this->_viewFiles); $this->context = $oldContext; return $output; }
/** * @return string|boolean the view file currently being rendered. False if no view file is being rendered. * 当前正在渲染的视图文件 */ public function getViewFile() { return end($this->_viewFiles); } /** * This method is invoked right before [[renderFile()]] renders a view file. * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event. * 前置事件,执行[renderFile()]时被调用,默认触发[[EVENT_BEFORE_RENDER]]事件 * If you override this method, make sure you call the parent implementation first. * @param string $viewFile the view file to be rendered. 要渲染的视图文件。 * @param array $params the parameter array passed to the [[render()]] method. * 参数数组传递到[render()]方法。 * @return boolean whether to continue rendering the view file. 是否继续渲染视图文件。 */ public function beforeRender($viewFile, $params) { $event = new ViewEvent([//实例化ViewEvent 'viewFile' => $viewFile, 'params' => $params, ]); $this->trigger(self::EVENT_BEFORE_RENDER, $event);//触发[EVENT_BEFORE_RENDER]事件 return $event->isValid;//判断是否继续渲染文件 } /** * This method is invoked right after [[renderFile()]] renders a view file. * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event. * 后置事件,在执行[renderFile()]方法后被调用,默认触发[[EVENT_AFTER_RENDER]]事件 * If you override this method, make sure you call the parent implementation first. * @param string $viewFile the view file being rendered.要渲染的视图文件。 * @param array $params the parameter array passed to the [[render()]] method. * 参数数组传递到[render()]方法。 * @param string $output the rendering result of the view file. Updates to this parameter * will be passed back and returned by [[renderFile()]]. * 返回视图渲染的结果 */ public function afterRender($viewFile, $params, &$output) { if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {//判断[EVENT_AFTER_RENDER]事件是否存在 $event = new ViewEvent([ 'viewFile' => $viewFile, 'params' => $params, 'output' => $output, ]); //触发[EVENT_AFTER_RENDER]事件 $this->trigger(self::EVENT_AFTER_RENDER, $event); $output = $event->output;//返回结果 } } /** * Renders a view file as a PHP script. * 返回一个视图文件当作PHP脚本 * This method treats the view file as a PHP script and includes the file. * It extracts the given parameters and makes them available in the view file. * The method captures the output of the included view file and returns it as a string. * 将传入的参数转换为变量,包含并执行view文件,返回执行结果 * This method should mainly be called by view renderer or [[renderFile()]]. * * @param string $_file_ the view file. 视图文件 * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. * @return string the rendering result 执行结果 */ public function renderPhpFile($_file_, $_params_ = []) { ob_start(); //打开输出缓冲 ob_implicit_flush(false); //关闭缓冲区 extract($_params_, EXTR_OVERWRITE);// 将一个数组转换为变量使用 require($_file_); return ob_get_clean();//得到缓冲区的内容并清除当前输出缓冲 } /** * Renders dynamic content returned by the given PHP statements. 渲染动态内容 * This method is mainly used together with content caching (fragment caching and page caching) * 用来聚合缓存的内容 * when some portions of the content (called *dynamic content*) should not be cached. * The dynamic content must be returned by some PHP statements. * 渲染某些被PHP语句返回的动态内容 * @param string $statements the PHP statements for generating the dynamic content.生成动态内容的PHP语句。 * @return string the placeholder of the dynamic content, or the dynamic content if there is no * active content cache currently. 动态内容占位符 如果当前没有有效的内容缓存,调用evaluateDynamicContent输出 */ public function renderDynamic($statements) { if (!empty($this->cacheStack)) {//动态内容的列表不为空 $n = count($this->dynamicPlaceholders);//统计动态内容条数 $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";//生成占位符 $this->addDynamicPlaceholder($placeholder, $statements);//添加动态内容占位符 return $placeholder; } else {//没有有效缓存 执行传入的PHP语句,返回执行结果 return $this->evaluateDynamicContent($statements); } } /** * Adds a placeholder for dynamic content. 添加一个动态内容占位符 * This method is internally used. 内部使用 * @param string $placeholder the placeholder name 占位符名称 * @param string $statements the PHP statements for generating the dynamic content * 生成动态内容的PHP语句 */ public function addDynamicPlaceholder($placeholder, $statements) { foreach ($this->cacheStack as $cache) { $cache->dynamicPlaceholders[$placeholder] = $statements;//添加动态内容占位符 } $this->dynamicPlaceholders[$placeholder] = $statements;//给当前视图添加动态内容占位符 } /** * Evaluates the given PHP statements. 给定的PHP语句的值 * This method is mainly used internally to implement dynamic content feature.内部使用实现动态内容功能 * @param string $statements the PHP statements to be evaluated. PHP语句进行计算 * @return mixed the return value of the PHP statements. PHP语句的值 */ public function evaluateDynamicContent($statements) { return eval($statements); } /** * Begins recording a block. * This method is a shortcut to beginning [[Block]] * 数据块开始的标记,该方法是开始[Block]的快捷方式 * 数据块可以在一个地方指定视图内容在另一个地方显示,通常和布局一起使用 * @param string $id the block ID. 数据块标识 * @param boolean $renderInPlace whether to render the block content in place. 是否渲染块内容。 * Defaults to false, meaning the captured block will not be displayed. * @return Block the Block widget instance 数据块部件实例 */ public function beginBlock($id, $renderInPlace = false) { return Block::begin([ 'id' => $id,//数据块唯一标识 'renderInPlace' => $renderInPlace,//是否显示标识 'view' => $this, ]); } /** * Ends recording a block. 数据块结束标识 */ public function endBlock() { Block::end(); } /** * Begins the rendering of content that is to be decorated by the specified view. * This method can be used to implement nested layout. For example, a layout can be embedded * in another layout file specified as '@app/views/layouts/base.php' like the following: * 开始指定的view渲染内容,用来实现嵌套布局,传入的第一个参数为布局文件的路径 * ~~~ * <?php $this->beginContent('@app/views/layouts/base.php'); ?> * ...layout content here... * <?php $this->endContent(); ?> * ~~~ * * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget. * This can be specified as either the view file path or path alias.布局文件的路径或路径别名。 * @param array $params the variables (name => value) to be extracted and made available in the decorative view. * 可以在视图中运用的参数 * @return ContentDecorator the ContentDecorator widget instance 部件实例 * @see ContentDecorator */ public function beginContent($viewFile, $params = []) { return ContentDecorator::begin([ 'viewFile' => $viewFile, 'params' => $params, 'view' => $this, ]); } /** * Ends the rendering of content.结束渲染内容 */ public function endContent() { ContentDecorator::end(); } /** * Begins fragment caching. 开始片段缓存 * This method will display cached content if it is available. * If not, it will start caching and would expect an [[endCache()]] * call to end the cache and save the content into cache. * 展示可用的缓存内容,否则将开始缓存内容直到出现[endCache()]方法 * A typical usage of fragment caching is as follows, * * ~~~ * if ($this->beginCache($id)) { * // ...generate content here * $this->endCache(); * } * ~~~ * * @param string $id a unique ID identifying the fragment to be cached.缓存片段的唯一标识 * @param array $properties initial property values for [[FragmentCache]]初始属性[FragmentCache] * @return boolean whether you should generate the content for caching. 是否生成缓存的内容。 * False if the cached version is available. */ public function beginCache($id, $properties = []) { $properties['id'] = $id; //片段标识 $properties['view'] = $this; //调用初始化属性 /* @var $cache FragmentCache */ $cache = FragmentCache::begin($properties); if ($cache->getCachedContent() !== false) { $this->endCache();//从缓存中读取到了缓存的内容,则渲染内容并返回 false,不再进行缓存 return false; } else { return true; } } /** * Ends fragment caching. 结束片段缓存 */ public function endCache() { FragmentCache::end(); } /** * Marks the beginning of a page.页面开始标记 */ public function beginPage() { ob_start(); //打开输出缓冲 ob_implicit_flush(false);//关闭缓冲区 $this->trigger(self::EVENT_BEGIN_PAGE); } /** * Marks the ending of a page. 页面结束标记 */ public function endPage() { $this->trigger(self::EVENT_END_PAGE); ob_end_flush();//关闭输出缓冲区 }
0 0
- View类
- view 类
- 类View
- View类
- View类
- View类
- View类详解(自定义view二)
- android.view.View类简介(一)
- View类简介
- view类控件
- View类详解
- 获得View类指针
- android view类 介绍
- android.view.GestureDetector类
- 创建Android View类
- 【Android】 View类详解
- 创建View类
- 计划--Android--View类
- 基于WampServer的个人网站本地开发配置
- Uniyt 官方人物换装(资源打包)
- 解决 编译内核出现kernel/timeconst.pl line 373问题
- 使用 wiredtiger 工具 wt 恢复数据
- Spring--IoC---基本XML的DI---设值注入
- View类
- 关于发送微信客服消息报44004错误的解决办法
- 常见的八种导致 APP 内存泄漏的问题
- 用cmake代替qmake
- try-with-resource
- 老毛桃
- 32位到64位:VS2013修改编译平台的方法
- Widget类
- 解决Centos 7安装完成之后无法联网