View.php 15.2 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\helpers\FileHelper;
12 13 14
use yii\widgets\Block;
use yii\widgets\ContentDecorator;
use yii\widgets\FragmentCache;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17
 * View represents a view object in the MVC pattern.
Qiang Xue committed
18
 *
Qiang Xue committed
19
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
Qiang Xue committed
20
 *
Qiang Xue committed
21 22 23 24 25
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
26
	/**
Qiang Xue committed
27
	 * @event Event an event that is triggered by [[beginPage()]].
28 29 30
	 */
	const EVENT_BEGIN_PAGE = 'beginPage';
	/**
Qiang Xue committed
31
	 * @event Event an event that is triggered by [[endPage()]].
32 33
	 */
	const EVENT_END_PAGE = 'endPage';
34
	/**
35
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
36 37 38
	 */
	const EVENT_BEFORE_RENDER = 'beforeRender';
	/**
39
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
40 41 42
	 */
	const EVENT_AFTER_RENDER = 'afterRender';

43
	/**
44
	 * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
45 46
	 */
	public $context;
Qiang Xue committed
47
	/**
Qiang Xue committed
48
	 * @var mixed custom parameters that are shared among view templates.
Qiang Xue committed
49
	 */
Alexander Makarov committed
50
	public $params = [];
Qiang Xue committed
51
	/**
Qiang Xue committed
52 53
	 * @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.
54 55 56
	 * For example, the following configuration enables both Smarty and Twig view renderers:
	 *
	 * ~~~
Alexander Makarov committed
57 58 59 60
	 * [
	 *     'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
	 *     'twig' => ['class' => 'yii\twig\ViewRenderer'],
	 * ]
61
	 * ~~~
Qiang Xue committed
62 63 64
	 *
	 * If no renderer is available for the given view file, the view file will be treated as a normal PHP
	 * and rendered via [[renderPhpFile()]].
Qiang Xue committed
65
	 */
66
	public $renderers;
67 68 69
	/**
	 * @var string the default view file extension. This will be appended to view file names if they don't have file extensions.
	 */
70
	public $defaultExtension = 'php';
71
	/**
72
	 * @var Theme|array the theme object or the configuration array for creating the theme object.
Qiang Xue committed
73
	 * If not set, it means theming is not enabled.
74
	 */
Qiang Xue committed
75
	public $theme;
Qiang Xue committed
76
	/**
Qiang Xue committed
77 78
	 * @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()]]
79
	 * to capture small fragments of a view. They can be later accessed somewhere else
Qiang Xue committed
80 81
	 * through this property.
	 */
Qiang Xue committed
82
	public $blocks;
Qiang Xue committed
83 84
	/**
	 * @var array a list of currently active fragment cache widgets. This property
85 86
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
87
	 */
Alexander Makarov committed
88
	public $cacheStack = [];
Qiang Xue committed
89 90
	/**
	 * @var array a list of placeholders for embedding dynamic contents. This property
91 92
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
93
	 */
Alexander Makarov committed
94
	public $dynamicPlaceholders = [];
95

96
	/**
97 98
	 * @var array the view files currently being rendered. There may be multiple view files being
	 * rendered at a moment because one may render a view file within another.
99
	 */
100
	private $_viewFiles = [];
Qiang Xue committed
101 102


Qiang Xue committed
103
	/**
Qiang Xue committed
104
	 * Initializes the view component.
Qiang Xue committed
105
	 */
Qiang Xue committed
106
	public function init()
Qiang Xue committed
107
	{
Qiang Xue committed
108 109
		parent::init();
		if (is_array($this->theme)) {
110 111 112
			if (!isset($this->theme['class'])) {
				$this->theme['class'] = 'yii\base\Theme';
			}
Qiang Xue committed
113
			$this->theme = Yii::createObject($this->theme);
Qiang Xue committed
114 115 116
		}
	}

Qiang Xue committed
117
	/**
Qiang Xue committed
118
	 * Renders a view.
Qiang Xue committed
119
	 *
120
	 * The view to be rendered can be specified in one of the following formats:
Qiang Xue committed
121
	 *
122 123 124 125 126 127
	 * - 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.
	 * - 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 [[module]].
	 * - resolving any other format will be performed via [[ViewContext::findViewFile()]].
Qiang Xue committed
128 129 130
	 *
	 * @param string $view the view name. Please refer to [[Controller::findViewFile()]]
	 * and [[Widget::findViewFile()]] on how to specify this parameter.
Qiang Xue committed
131
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
132 133
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
134
	 * @return string the rendering result
Qiang Xue committed
135
	 * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
136
	 * @see renderFile()
Qiang Xue committed
137
	 */
138
	public function render($view, $params = [], $context = null)
Qiang Xue committed
139
	{
140 141 142 143 144 145 146 147 148 149 150
		$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 that the view should be used to search the view file. If null,
	 * existing [[context]] will be used.
	 * @return string the view file path. Note that the file may not exist.
151
	 * @throws InvalidCallException if [[context]] is required and invalid.
152 153 154 155 156 157 158 159 160
	 */
	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, '/');
161
		} elseif (strncmp($view, '/', 1) === 0) {
162
			// e.g. "/site/index"
163 164 165 166 167
			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.");
			}
Qiang Xue committed
168
		} else {
169 170 171 172
			// context required
			if ($context === null) {
				$context = $this->context;
			}
173
			if ($context instanceof ViewContextInterface) {
174 175
				$file = $context->findViewFile($view);
			} else {
176
				throw new InvalidCallException("Unable to locate view file for view '$view': no active view context.");
177
			}
Qiang Xue committed
178
		}
179

180 181 182 183 184 185 186 187
		if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
			return $file;
		}
		$path = $file . '.' . $this->defaultExtension;
		if ($this->defaultExtension !== 'php' && !is_file($path)) {
			$path = $file . '.php';
		}
		return $path;
Qiang Xue committed
188 189
	}

Qiang Xue committed
190 191
	/**
	 * Renders a view file.
Qiang Xue committed
192
	 *
Qiang Xue committed
193 194
	 * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
	 * as it is available.
Qiang Xue committed
195
	 *
Qiang Xue committed
196 197 198 199 200 201
	 * The method will call [[FileHelper::localize()]] to localize the view file.
	 *
	 * If [[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.
	 *
Qiang Xue committed
202
	 * @param string $viewFile the view file. This can be either a file path or a path alias.
Qiang Xue committed
203
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
204 205
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
Qiang Xue committed
206
	 * @return string the rendering result
Qiang Xue committed
207
	 * @throws InvalidParamException if the view file does not exist
Qiang Xue committed
208
	 */
Alexander Makarov committed
209
	public function renderFile($viewFile, $params = [], $context = null)
Qiang Xue committed
210
	{
Qiang Xue committed
211
		$viewFile = Yii::getAlias($viewFile);
212 213 214
		if ($this->theme !== null) {
			$viewFile = $this->theme->applyTo($viewFile);
		}
Qiang Xue committed
215 216 217 218 219 220
		if (is_file($viewFile)) {
			$viewFile = FileHelper::localize($viewFile);
		} else {
			throw new InvalidParamException("The view file does not exist: $viewFile");
		}

Qiang Xue committed
221
		$oldContext = $this->context;
Qiang Xue committed
222 223 224
		if ($context !== null) {
			$this->context = $context;
		}
225
		$output = '';
226 227
		$this->_viewFiles[] = $viewFile;

228
		if ($this->beforeRender()) {
Qiang Xue committed
229
			Yii::trace("Rendering view file: $viewFile", __METHOD__);
Qiang Xue committed
230 231
			$ext = pathinfo($viewFile, PATHINFO_EXTENSION);
			if (isset($this->renderers[$ext])) {
Qiang Xue committed
232
				if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
Qiang Xue committed
233 234 235 236 237
					$this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
				}
				/** @var ViewRenderer $renderer */
				$renderer = $this->renderers[$ext];
				$output = $renderer->render($this, $viewFile, $params);
238 239 240
			} else {
				$output = $this->renderPhpFile($viewFile, $params);
			}
241
			$this->afterRender($output);
Qiang Xue committed
242
		}
Qiang Xue committed
243

244
		array_pop($this->_viewFiles);
Qiang Xue committed
245 246 247
		$this->context = $oldContext;

		return $output;
Qiang Xue committed
248 249
	}

250 251 252 253 254 255 256 257
	/**
	 * @return string|boolean the view file currently being rendered. False if no view file is being rendered.
	 */
	public function getViewFile()
	{
		return end($this->_viewFiles);
	}

258 259 260 261 262 263
	/**
	 * This method is invoked right before [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @return boolean whether to continue rendering the view file.
	 */
264
	public function beforeRender()
265
	{
266
		$event = new ViewEvent;
267 268 269 270 271 272 273 274 275 276 277
		$this->trigger(self::EVENT_BEFORE_RENDER, $event);
		return $event->isValid;
	}

	/**
	 * This method is invoked right after [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @param string $output the rendering result of the view file. Updates to this parameter
	 * will be passed back and returned by [[renderFile()]].
	 */
278
	public function afterRender(&$output)
279 280
	{
		if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
281
			$event = new ViewEvent;
282 283 284 285 286 287
			$event->output = $output;
			$this->trigger(self::EVENT_AFTER_RENDER, $event);
			$output = $event->output;
		}
	}

Qiang Xue committed
288
	/**
Qiang Xue committed
289 290 291 292 293 294
	 * Renders a view file as a PHP script.
	 *
	 * 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.
	 *
Qiang Xue committed
295 296
	 * This method should mainly be called by view renderer or [[renderFile()]].
	 *
Qiang Xue committed
297 298 299
	 * @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
Qiang Xue committed
300
	 */
Alexander Makarov committed
301
	public function renderPhpFile($_file_, $_params_ = [])
Qiang Xue committed
302
	{
Qiang Xue committed
303 304 305 306 307
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
308 309
	}

Qiang Xue committed
310 311 312 313 314 315 316 317 318
	/**
	 * 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.
	 * @param string $statements the PHP statements for generating the dynamic content.
	 * @return string the placeholder of the dynamic content, or the dynamic content if there is no
	 * active content cache currently.
	 */
Qiang Xue committed
319 320
	public function renderDynamic($statements)
	{
Qiang Xue committed
321 322
		if (!empty($this->cacheStack)) {
			$n = count($this->dynamicPlaceholders);
Qiang Xue committed
323
			$placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
Qiang Xue committed
324
			$this->addDynamicPlaceholder($placeholder, $statements);
Qiang Xue committed
325 326 327 328 329 330
			return $placeholder;
		} else {
			return $this->evaluateDynamicContent($statements);
		}
	}

Qiang Xue committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	/**
	 * 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
	 */
	public function addDynamicPlaceholder($placeholder, $statements)
	{
		foreach ($this->cacheStack as $cache) {
			$cache->dynamicPlaceholders[$placeholder] = $statements;
		}
		$this->dynamicPlaceholders[$placeholder] = $statements;
	}

	/**
	 * Evaluates the given PHP statements.
	 * This method is mainly used internally to implement dynamic content feature.
	 * @param string $statements the PHP statements to be evaluated.
	 * @return mixed the return value of the PHP statements.
	 */
Qiang Xue committed
351 352 353 354 355
	public function evaluateDynamicContent($statements)
	{
		return eval($statements);
	}

Qiang Xue committed
356
	/**
Qiang Xue committed
357
	 * Begins recording a block.
358
	 * This method is a shortcut to beginning [[Block]]
Qiang Xue committed
359 360 361
	 * @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.
362
	 * @return Block the Block widget instance
Qiang Xue committed
363
	 */
Qiang Xue committed
364
	public function beginBlock($id, $renderInPlace = false)
Qiang Xue committed
365
	{
Alexander Makarov committed
366
		return Block::begin([
Qiang Xue committed
367 368
			'id' => $id,
			'renderInPlace' => $renderInPlace,
369
			'view' => $this,
Alexander Makarov committed
370
		]);
Qiang Xue committed
371 372 373
	}

	/**
Qiang Xue committed
374
	 * Ends recording a block.
Qiang Xue committed
375
	 */
Qiang Xue committed
376
	public function endBlock()
Qiang Xue committed
377
	{
378
		Block::end();
Qiang Xue committed
379 380
	}

Qiang Xue committed
381 382
	/**
	 * Begins the rendering of content that is to be decorated by the specified view.
Qiang Xue committed
383
	 * This method can be used to implement nested layout. For example, a layout can be embedded
Sergey Gonimar committed
384
	 * in another layout file specified as '@app/views/layouts/base.php' like the following:
Qiang Xue committed
385 386
	 *
	 * ~~~
Sergey Gonimar committed
387
	 * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
Qiang Xue committed
388 389 390 391 392 393
	 * ...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.
resurtm committed
394
	 * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
395 396
	 * @return ContentDecorator the ContentDecorator widget instance
	 * @see ContentDecorator
Qiang Xue committed
397
	 */
Alexander Makarov committed
398
	public function beginContent($viewFile, $params = [])
Qiang Xue committed
399
	{
Alexander Makarov committed
400
		return ContentDecorator::begin([
Qiang Xue committed
401
			'viewFile' => $viewFile,
Qiang Xue committed
402
			'params' => $params,
403
			'view' => $this,
Alexander Makarov committed
404
		]);
Qiang Xue committed
405 406 407 408 409 410 411
	}

	/**
	 * Ends the rendering of content.
	 */
	public function endContent()
	{
412
		ContentDecorator::end();
Qiang Xue committed
413 414
	}

415 416 417 418 419 420 421 422
	/**
	 * 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.
	 * A typical usage of fragment caching is as follows,
	 *
	 * ~~~
resurtm committed
423
	 * if ($this->beginCache($id)) {
424 425 426 427 428 429
	 *     // ...generate content here
	 *     $this->endCache();
	 * }
	 * ~~~
	 *
	 * @param string $id a unique ID identifying the fragment to be cached.
430
	 * @param array $properties initial property values for [[FragmentCache]]
431 432 433
	 * @return boolean whether you should generate the content for caching.
	 * False if the cached version is available.
	 */
Alexander Makarov committed
434
	public function beginCache($id, $properties = [])
435 436
	{
		$properties['id'] = $id;
437
		$properties['view'] = $this;
slavcodev committed
438
		/** @var FragmentCache $cache */
439
		$cache = FragmentCache::begin($properties);
Qiang Xue committed
440
		if ($cache->getCachedContent() !== false) {
441 442 443 444 445 446 447 448 449 450 451 452
			$this->endCache();
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Ends fragment caching.
	 */
	public function endCache()
	{
453
		FragmentCache::end();
454
	}
455 456

	/**
Alexander Makarov committed
457
	 * Marks the beginning of a page.
458 459 460 461 462
	 */
	public function beginPage()
	{
		ob_start();
		ob_implicit_flush(false);
463 464

		$this->trigger(self::EVENT_BEGIN_PAGE);
465 466 467
	}

	/**
Alexander Makarov committed
468
	 * Marks the ending of a page.
469 470 471
	 */
	public function endPage()
	{
472
		$this->trigger(self::EVENT_END_PAGE);
Alexander Makarov committed
473
		ob_end_flush();
474
	}
Zander Baldwin committed
475
}