View.php 14.1 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\base\Application;
Qiang Xue committed
12
use yii\helpers\FileHelper;
Qiang Xue committed
13

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * View represents a view object in the MVC pattern.
Qiang Xue committed
16
 *
Qiang Xue committed
17
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
Qiang Xue committed
18
 *
Qiang Xue committed
19 20 21 22 23
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
Qiang Xue committed
24
	/**
Qiang Xue committed
25 26
	 * @var object the object that owns this view. This can be a controller, a widget, or any other object.
	 */
Qiang Xue committed
27
	public $context;
Qiang Xue committed
28
	/**
Qiang Xue committed
29
	 * @var mixed custom parameters that are shared among view templates.
Qiang Xue committed
30
	 */
Qiang Xue committed
31
	public $params;
Qiang Xue committed
32
	/**
Qiang Xue committed
33 34
	 * @var ViewRenderer|array the view renderer object or the configuration array for
	 * creating the view renderer. If not set, view files will be treated as normal PHP files.
Qiang Xue committed
35
	 */
Qiang Xue committed
36
	public $renderer;
37
	/**
Qiang Xue committed
38 39
	 * @var Theme|array the theme object or the configuration array for creating the theme.
	 * If not set, it means theming is not enabled.
40
	 */
Qiang Xue committed
41
	public $theme;
Qiang Xue committed
42 43 44 45 46 47
	/**
	 * @var array a list of named output clips. You can call [[beginClip()]] and [[endClip()]]
	 * to capture small fragments of a view. They can be later accessed at somewhere else
	 * through this property.
	 */
	public $clips;
Qiang Xue committed
48
	/**
Qiang Xue committed
49 50 51 52 53 54 55 56 57 58 59 60
	 * @var Widget[] the widgets that are currently being rendered (not ended). This property
	 * is maintained by [[beginWidget()]] and [[endWidget()]] methods. Do not modify it directly.
	 */
	public $widgetStack = array();
	/**
	 * @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.
	 */
	public $cacheStack = array();
	/**
	 * @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.
Qiang Xue committed
61
	 */
Qiang Xue committed
62
	public $dynamicPlaceholders = array();
Qiang Xue committed
63 64


Qiang Xue committed
65
	/**
Qiang Xue committed
66
	 * Initializes the view component.
Qiang Xue committed
67
	 */
Qiang Xue committed
68
	public function init()
Qiang Xue committed
69
	{
Qiang Xue committed
70 71 72 73 74 75
		parent::init();
		if (is_array($this->renderer)) {
			$this->renderer = Yii::createObject($this->renderer);
		}
		if (is_array($this->theme)) {
			$this->theme = Yii::createObject($this->theme);
Qiang Xue committed
76 77 78
		}
	}

Qiang Xue committed
79
	/**
Qiang Xue committed
80
	 * Renders a view.
Qiang Xue committed
81
	 *
Qiang Xue committed
82 83
	 * This method will call [[findViewFile()]] to convert the view name into the corresponding view
	 * file path, and it will then call [[renderFile()]] to render the view.
Qiang Xue committed
84
	 *
Qiang Xue committed
85
	 * @param string $view the view name. Please refer to [[findViewFile()]] on how to specify this parameter.
Qiang Xue committed
86
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
87 88
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
89
	 * @return string the rendering result
Qiang Xue committed
90 91 92
	 * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
	 * @see renderFile
	 * @see findViewFile
Qiang Xue committed
93
	 */
Qiang Xue committed
94
	public function render($view, $params = array(), $context = null)
Qiang Xue committed
95
	{
Qiang Xue committed
96 97
		$viewFile = $this->findViewFile($context, $view);
		return $this->renderFile($viewFile, $params, $context);
Qiang Xue committed
98 99
	}

Qiang Xue committed
100 101
	/**
	 * Renders a view file.
Qiang Xue committed
102
	 *
Qiang Xue committed
103 104
	 * 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
105
	 *
Qiang Xue committed
106 107 108 109 110 111
	 * 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
112
	 * @param string $viewFile the view file. This can be either a file path or a path alias.
Qiang Xue committed
113
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
114 115
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
Qiang Xue committed
116
	 * @return string the rendering result
Qiang Xue committed
117
	 * @throws InvalidParamException if the view file does not exist
Qiang Xue committed
118
	 */
Qiang Xue committed
119
	public function renderFile($viewFile, $params = array(), $context = null)
Qiang Xue committed
120
	{
Qiang Xue committed
121 122 123 124 125 126 127 128 129 130
		$viewFile = Yii::getAlias($viewFile);
		if (is_file($viewFile)) {
			if ($this->theme !== null) {
				$viewFile = $this->theme->applyTo($viewFile);
			}
			$viewFile = FileHelper::localize($viewFile);
		} else {
			throw new InvalidParamException("The view file does not exist: $viewFile");
		}

Qiang Xue committed
131
		$oldContext = $this->context;
Qiang Xue committed
132 133 134
		if ($context !== null) {
			$this->context = $context;
		}
Qiang Xue committed
135

Qiang Xue committed
136
		if ($this->renderer !== null) {
Qiang Xue committed
137
			$output = $this->renderer->render($this, $viewFile, $params);
Qiang Xue committed
138
		} else {
Qiang Xue committed
139
			$output = $this->renderPhpFile($viewFile, $params);
Qiang Xue committed
140
		}
Qiang Xue committed
141 142 143 144

		$this->context = $oldContext;

		return $output;
Qiang Xue committed
145 146 147
	}

	/**
Qiang Xue committed
148 149 150 151 152 153
	 * 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
154 155
	 * This method should mainly be called by view renderer or [[renderFile()]].
	 *
Qiang Xue committed
156 157 158
	 * @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
159
	 */
Qiang Xue committed
160
	public function renderPhpFile($_file_, $_params_ = array())
Qiang Xue committed
161
	{
Qiang Xue committed
162 163 164 165 166
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
167 168
	}

Qiang Xue committed
169 170 171 172 173 174 175 176 177
	/**
	 * 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
178 179
	public function renderDynamic($statements)
	{
Qiang Xue committed
180 181
		if (!empty($this->cacheStack)) {
			$n = count($this->dynamicPlaceholders);
Qiang Xue committed
182
			$placeholder = "<![CDATA[YDP-$n]]>";
Qiang Xue committed
183
			$this->addDynamicPlaceholder($placeholder, $statements);
Qiang Xue committed
184 185 186 187 188 189
			return $placeholder;
		} else {
			return $this->evaluateDynamicContent($statements);
		}
	}

Qiang Xue committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	/**
	 * 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
210 211 212 213 214
	public function evaluateDynamicContent($statements)
	{
		return eval($statements);
	}

Qiang Xue committed
215 216 217 218 219 220 221 222 223 224 225
	/**
	 * Finds the view file based on the given view name.
	 *
	 * A view name 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.
	 * - absolute path within 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 currently
	 *   active module.
Qiang Xue committed
226 227
	 * - relative path (e.g. "index"): the actual view file will be looked for under [[Controller::viewPath|viewPath]]
	 *   of the context object, assuming the context is either a [[Controller]] or a [[Widget]].
Qiang Xue committed
228 229 230
	 *
	 * If the view name does not contain a file extension, it will use the default one `.php`.
	 *
Qiang Xue committed
231
	 * @param object $context the view context object
Qiang Xue committed
232 233
	 * @param string $view the view name or the path alias of the view file.
	 * @return string the view file path. Note that the file may not exist.
Qiang Xue committed
234 235
	 * @throws InvalidParamException if the view file is an invalid path alias or the context cannot be
	 * used to determine the actual view file corresponding to the specified view.
Qiang Xue committed
236 237 238
	 */
	protected function findViewFile($context, $view)
	{
Qiang Xue committed
239 240 241 242
		if (strncmp($view, '@', 1) === 0) {
			// e.g. "@app/views/main"
			$file = Yii::getAlias($view);
		} elseif (strncmp($view, '//', 2) === 0) {
Qiang Xue committed
243 244 245 246
			// e.g. "//layouts/main"
			$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
		} elseif (strncmp($view, '/', 1) === 0) {
			// e.g. "/site/index"
Qiang Xue committed
247 248 249 250 251 252
			$file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
		} elseif ($context instanceof Controller || $context instanceof Widget) {
			/** @var $context Controller|Widget */
			$file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
		} else {
			throw new InvalidParamException("Unable to resolve the view file for '$view'.");
Qiang Xue committed
253 254
		}

Qiang Xue committed
255
		return FileHelper::getExtension($file) === '' ? $file . '.php' : $file;
Qiang Xue committed
256 257
	}

Qiang Xue committed
258 259 260 261 262 263 264
	/**
	 * Creates a widget.
	 * This method will use [[Yii::createObject()]] to create the widget.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @return Widget the newly created widget instance
	 */
Qiang Xue committed
265 266 267
	public function createWidget($class, $properties = array())
	{
		$properties['class'] = $class;
Qiang Xue committed
268
		return Yii::createObject($properties, $this->context);
Qiang Xue committed
269 270
	}

Qiang Xue committed
271 272 273 274 275 276 277 278 279 280
	/**
	 * Creates and runs a widget.
	 * Compared with [[createWidget()]], this method does one more thing: it will
	 * run the widget after it is created.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @param boolean $captureOutput whether to capture the output of the widget and return it as a string
	 * @return string|Widget if $captureOutput is true, the output of the widget will be returned;
	 * otherwise the widget object will be returned.
	 */
Qiang Xue committed
281
	public function widget($class, $properties = array(), $captureOutput = false)
Qiang Xue committed
282
	{
Qiang Xue committed
283 284 285 286 287 288 289 290 291 292 293
		if ($captureOutput) {
			ob_start();
			ob_implicit_flush(false);
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return ob_get_clean();
		} else {
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return $widget;
		}
Qiang Xue committed
294 295
	}

Qiang Xue committed
296 297
	/**
	 * Begins a widget.
Qiang Xue committed
298 299 300 301
	 * This method is similar to [[createWidget()]] except that it will expect a matching
	 * [[endWidget()]] call after this.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
Qiang Xue committed
302 303
	 * @return Widget the widget instance
	 */
Qiang Xue committed
304 305
	public function beginWidget($class, $properties = array())
	{
306
		$widget = $this->createWidget($class, $properties);
Qiang Xue committed
307
		$this->widgetStack[] = $widget;
308
		return $widget;
Qiang Xue committed
309 310
	}

Qiang Xue committed
311 312 313 314 315 316
	/**
	 * Ends a widget.
	 * Note that the rendering result of the widget is directly echoed out.
	 * If you want to capture the rendering result of a widget, you may use
	 * [[createWidget()]] and [[Widget::run()]].
	 * @return Widget the widget instance
Qiang Xue committed
317
	 * @throws InvalidCallException if [[beginWidget()]] and [[endWidget()]] calls are not properly nested
Qiang Xue committed
318
	 */
Qiang Xue committed
319
	public function endWidget()
Qiang Xue committed
320
	{
Qiang Xue committed
321
		$widget = array_pop($this->widgetStack);
Qiang Xue committed
322
		if ($widget instanceof Widget) {
Qiang Xue committed
323
			$widget->run();
Qiang Xue committed
324
			return $widget;
325
		} else {
Qiang Xue committed
326
			throw new InvalidCallException("Unmatched beginWidget() and endWidget() calls.");
Qiang Xue committed
327 328 329
		}
	}

Qiang Xue committed
330 331 332 333 334 335 336
	/**
	 * Begins recording a clip.
	 * This method is a shortcut to beginning [[yii\widgets\Clip]]
	 * @param string $id the clip ID.
	 * @param boolean $renderInPlace whether to render the clip content in place.
	 * Defaults to false, meaning the captured clip will not be displayed.
	 * @return \yii\widgets\Clip the Clip widget instance
Qiang Xue committed
337
	 * @see \yii\widgets\Clip
Qiang Xue committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
	 */
	public function beginClip($id, $renderInPlace = false)
	{
		return $this->beginWidget('yii\widgets\Clip', array(
			'id' => $id,
			'renderInPlace' => $renderInPlace,
			'view' => $this,
		));
	}

	/**
	 * Ends recording a clip.
	 */
	public function endClip()
	{
		$this->endWidget();
	}

Qiang Xue committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
	/**
	 * Begins the rendering of content that is to be decorated by the specified view.
	 * @param string $view the name of the view that will be used to decorate the content enclosed by this widget.
	 * Please refer to [[View::findViewFile()]] on how to set this property.
	 * @param array $params the variables (name=>value) to be extracted and made available in the decorative view.
	 * @return \yii\widgets\ContentDecorator the ContentDecorator widget instance
	 * @see \yii\widgets\ContentDecorator
	 */
	public function beginContent($view, $params = array())
	{
		return $this->beginWidget('yii\widgets\ContentDecorator', array(
			'view' => $this,
			'viewName' => $view,
			'params' => $params,
		));
	}

	/**
	 * Ends the rendering of content.
	 */
	public function endContent()
	{
		$this->endWidget();
	}

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	/**
	 * 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,
	 *
	 * ~~~
	 * if($this->beginCache($id)) {
	 *     // ...generate content here
	 *     $this->endCache();
	 * }
	 * ~~~
	 *
	 * @param string $id a unique ID identifying the fragment to be cached.
Qiang Xue committed
396
	 * @param array $properties initial property values for [[\yii\widgets\FragmentCache]]
397 398 399 400 401 402
	 * @return boolean whether you should generate the content for caching.
	 * False if the cached version is available.
	 */
	public function beginCache($id, $properties = array())
	{
		$properties['id'] = $id;
Qiang Xue committed
403
		$properties['view'] = $this;
Qiang Xue committed
404
		/** @var $cache \yii\widgets\FragmentCache */
Qiang Xue committed
405
		$cache = $this->beginWidget('yii\widgets\FragmentCache', $properties);
Qiang Xue committed
406
		if ($cache->getCachedContent() !== false) {
407 408 409 410 411 412 413 414 415 416 417 418 419 420
			$this->endCache();
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Ends fragment caching.
	 */
	public function endCache()
	{
		$this->endWidget();
	}
Qiang Xue committed
421
}