CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.4 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • Helper
  • HelperCollection
  • JsonView
  • MediaView
  • ScaffoldView
  • ThemeView
  • View
  • ViewBlock
  • XmlView
   1: <?php
   2: /**
   3:  * Methods for displaying presentation data in the view.
   4:  *
   5:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
   6:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
   7:  *
   8:  * Licensed under The MIT License
   9:  * For full copyright and license information, please see the LICENSE.txt
  10:  * Redistributions of files must retain the above copyright notice.
  11:  *
  12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13:  * @link          http://cakephp.org CakePHP(tm) Project
  14:  * @package       Cake.View
  15:  * @since         CakePHP(tm) v 0.10.0.1076
  16:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
  17:  */
  18: 
  19: App::uses('HelperCollection', 'View');
  20: App::uses('AppHelper', 'View/Helper');
  21: App::uses('Router', 'Routing');
  22: App::uses('ViewBlock', 'View');
  23: App::uses('CakeEvent', 'Event');
  24: App::uses('CakeEventManager', 'Event');
  25: App::uses('CakeResponse', 'Network');
  26: 
  27: /**
  28:  * View, the V in the MVC triad. View interacts with Helpers and view variables passed
  29:  * in from the controller to render the results of the controller action. Often this is HTML,
  30:  * but can also take the form of JSON, XML, PDF's or streaming files.
  31:  *
  32:  * CakePHP uses a two-step-view pattern. This means that the view content is rendered first,
  33:  * and then inserted into the selected layout. This also means you can pass data from the view to the
  34:  * layout using `$this->set()`
  35:  *
  36:  * Since 2.1, the base View class also includes support for themes by default. Theme views are regular
  37:  * view files that can provide unique HTML and static assets. If theme views are not found for the
  38:  * current view the default app view files will be used. You can set `$this->theme = 'mytheme'`
  39:  * in your Controller to use the Themes.
  40:  *
  41:  * Example of theme path with `$this->theme = 'SuperHot';` Would be `app/View/Themed/SuperHot/Posts`
  42:  *
  43:  * @package       Cake.View
  44:  * @property      CacheHelper $Cache
  45:  * @property      FormHelper $Form
  46:  * @property      HtmlHelper $Html
  47:  * @property      JsHelper $Js
  48:  * @property      NumberHelper $Number
  49:  * @property      PaginatorHelper $Paginator
  50:  * @property      RssHelper $Rss
  51:  * @property      SessionHelper $Session
  52:  * @property      TextHelper $Text
  53:  * @property      TimeHelper $Time
  54:  * @property      ViewBlock $Blocks
  55:  */
  56: class View extends Object {
  57: 
  58: /**
  59:  * Helpers collection
  60:  *
  61:  * @var HelperCollection
  62:  */
  63:     public $Helpers;
  64: 
  65: /**
  66:  * ViewBlock instance.
  67:  *
  68:  * @var ViewBlock
  69:  */
  70:     public $Blocks;
  71: 
  72: /**
  73:  * Name of the plugin.
  74:  *
  75:  * @link http://manual.cakephp.org/chapter/plugins
  76:  * @var string
  77:  */
  78:     public $plugin = null;
  79: 
  80: /**
  81:  * Name of the controller.
  82:  *
  83:  * @var string Name of controller
  84:  */
  85:     public $name = null;
  86: 
  87: /**
  88:  * Current passed params
  89:  *
  90:  * @var mixed
  91:  */
  92:     public $passedArgs = array();
  93: 
  94: /**
  95:  * An array of names of built-in helpers to include.
  96:  *
  97:  * @var mixed A single name as a string or a list of names as an array.
  98:  */
  99:     public $helpers = array();
 100: 
 101: /**
 102:  * Path to View.
 103:  *
 104:  * @var string Path to View
 105:  */
 106:     public $viewPath = null;
 107: 
 108: /**
 109:  * Variables for the view
 110:  *
 111:  * @var array
 112:  */
 113:     public $viewVars = array();
 114: 
 115: /**
 116:  * Name of view to use with this View.
 117:  *
 118:  * @var string
 119:  */
 120:     public $view = null;
 121: 
 122: /**
 123:  * Name of layout to use with this View.
 124:  *
 125:  * @var string
 126:  */
 127:     public $layout = 'default';
 128: 
 129: /**
 130:  * Path to Layout.
 131:  *
 132:  * @var string Path to Layout
 133:  */
 134:     public $layoutPath = null;
 135: 
 136: /**
 137:  * Turns on or off CakePHP's conventional mode of applying layout files. On by default.
 138:  * Setting to off means that layouts will not be automatically applied to rendered views.
 139:  *
 140:  * @var boolean
 141:  */
 142:     public $autoLayout = true;
 143: 
 144: /**
 145:  * File extension. Defaults to CakePHP's template ".ctp".
 146:  *
 147:  * @var string
 148:  */
 149:     public $ext = '.ctp';
 150: 
 151: /**
 152:  * Sub-directory for this view file. This is often used for extension based routing.
 153:  * Eg. With an `xml` extension, $subDir would be `xml/`
 154:  *
 155:  * @var string
 156:  */
 157:     public $subDir = null;
 158: 
 159: /**
 160:  * Theme name.
 161:  *
 162:  * @var string
 163:  */
 164:     public $theme = null;
 165: 
 166: /**
 167:  * Used to define methods a controller that will be cached.
 168:  *
 169:  * @see Controller::$cacheAction
 170:  * @var mixed
 171:  */
 172:     public $cacheAction = false;
 173: 
 174: /**
 175:  * Holds current errors for the model validation.
 176:  *
 177:  * @var array
 178:  */
 179:     public $validationErrors = array();
 180: 
 181: /**
 182:  * True when the view has been rendered.
 183:  *
 184:  * @var boolean
 185:  */
 186:     public $hasRendered = false;
 187: 
 188: /**
 189:  * List of generated DOM UUIDs.
 190:  *
 191:  * @var array
 192:  */
 193:     public $uuids = array();
 194: 
 195: /**
 196:  * An instance of a CakeRequest object that contains information about the current request.
 197:  * This object contains all the information about a request and several methods for reading
 198:  * additional information about the request.
 199:  *
 200:  * @var CakeRequest
 201:  */
 202:     public $request;
 203: 
 204: /**
 205:  * Reference to the Response object
 206:  *
 207:  * @var CakeResponse
 208:  */
 209:     public $response;
 210: 
 211: /**
 212:  * The Cache configuration View will use to store cached elements. Changing this will change
 213:  * the default configuration elements are stored under. You can also choose a cache config
 214:  * per element.
 215:  *
 216:  * @var string
 217:  * @see View::element()
 218:  */
 219:     public $elementCache = 'default';
 220: 
 221: /**
 222:  * Element cache settings
 223:  *
 224:  * @var array
 225:  * @see View::_elementCache();
 226:  * @see View::_renderElement
 227:  */
 228:     public $elementCacheSettings = array();
 229: 
 230: /**
 231:  * List of variables to collect from the associated controller.
 232:  *
 233:  * @var array
 234:  */
 235:     protected $_passedVars = array(
 236:         'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'theme',
 237:         'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction'
 238:     );
 239: 
 240: /**
 241:  * Scripts (and/or other <head /> tags) for the layout.
 242:  *
 243:  * @var array
 244:  */
 245:     protected $_scripts = array();
 246: 
 247: /**
 248:  * Holds an array of paths.
 249:  *
 250:  * @var array
 251:  */
 252:     protected $_paths = array();
 253: 
 254: /**
 255:  * The names of views and their parents used with View::extend();
 256:  *
 257:  * @var array
 258:  */
 259:     protected $_parents = array();
 260: 
 261: /**
 262:  * The currently rendering view file. Used for resolving parent files.
 263:  *
 264:  * @var string
 265:  */
 266:     protected $_current = null;
 267: 
 268: /**
 269:  * Currently rendering an element. Used for finding parent fragments
 270:  * for elements.
 271:  *
 272:  * @var string
 273:  */
 274:     protected $_currentType = '';
 275: 
 276: /**
 277:  * Content stack, used for nested templates that all use View::extend();
 278:  *
 279:  * @var array
 280:  */
 281:     protected $_stack = array();
 282: 
 283: /**
 284:  * Instance of the CakeEventManager this View object is using
 285:  * to dispatch inner events. Usually the manager is shared with
 286:  * the controller, so it it possible to register view events in
 287:  * the controller layer.
 288:  *
 289:  * @var CakeEventManager
 290:  */
 291:     protected $_eventManager = null;
 292: 
 293: /**
 294:  * Whether the event manager was already configured for this object
 295:  *
 296:  * @var boolean
 297:  */
 298:     protected $_eventManagerConfigured = false;
 299: 
 300: /**
 301:  * Constant for view file type 'view'
 302:  *
 303:  * @var string
 304:  */
 305:     const TYPE_VIEW = 'view';
 306: 
 307: /**
 308:  * Constant for view file type 'element'
 309:  *
 310:  * @var string
 311:  */
 312:     const TYPE_ELEMENT = 'element';
 313: 
 314: /**
 315:  * Constant for view file type 'layout'
 316:  *
 317:  * @var string
 318:  */
 319:     const TYPE_LAYOUT = 'layout';
 320: 
 321: /**
 322:  * Constructor
 323:  *
 324:  * @param Controller $controller A controller object to pull View::_passedVars from.
 325:  */
 326:     public function __construct(Controller $controller = null) {
 327:         if (is_object($controller)) {
 328:             $count = count($this->_passedVars);
 329:             for ($j = 0; $j < $count; $j++) {
 330:                 $var = $this->_passedVars[$j];
 331:                 $this->{$var} = $controller->{$var};
 332:             }
 333:             $this->_eventManager = $controller->getEventManager();
 334:         }
 335:         if (empty($this->request) && !($this->request = Router::getRequest(true))) {
 336:             $this->request = new CakeRequest(null, false);
 337:             $this->request->base = '';
 338:             $this->request->here = $this->request->webroot = '/';
 339:         }
 340:         if (is_object($controller) && isset($controller->response)) {
 341:             $this->response = $controller->response;
 342:         } else {
 343:             $this->response = new CakeResponse();
 344:         }
 345:         $this->Helpers = new HelperCollection($this);
 346:         $this->Blocks = new ViewBlock();
 347:         $this->loadHelpers();
 348:         parent::__construct();
 349:     }
 350: 
 351: /**
 352:  * Returns the CakeEventManager manager instance that is handling any callbacks.
 353:  * You can use this instance to register any new listeners or callbacks to the
 354:  * controller events, or create your own events and trigger them at will.
 355:  *
 356:  * @return CakeEventManager
 357:  */
 358:     public function getEventManager() {
 359:         if (empty($this->_eventManager)) {
 360:             $this->_eventManager = new CakeEventManager();
 361:         }
 362:         if (!$this->_eventManagerConfigured) {
 363:             $this->_eventManager->attach($this->Helpers);
 364:             $this->_eventManagerConfigured = true;
 365:         }
 366:         return $this->_eventManager;
 367:     }
 368: 
 369: /**
 370:  * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
 371:  *
 372:  * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
 373:  * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
 374:  *
 375:  * @param string $name Name of template file in the/app/View/Elements/ folder,
 376:  *   or `MyPlugin.template` to use the template element from MyPlugin. If the element
 377:  *   is not found in the plugin, the normal view path cascade will be searched.
 378:  * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
 379:  * @param array $options Array of options. Possible keys are:
 380:  * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
 381:  *   If an array, the following keys can be used:
 382:  *   - `config` - Used to store the cached element in a custom cache configuration.
 383:  *   - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
 384:  * - `plugin` - (deprecated!) Load an element from a specific plugin. This option is deprecated, and
 385:  *              will be removed in CakePHP 3.0. Use `Plugin.element_name` instead.
 386:  * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
 387:  *   Defaults to false.
 388:  * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices.
 389:  * @return string Rendered Element
 390:  */
 391:     public function element($name, $data = array(), $options = array()) {
 392:         $file = $plugin = null;
 393: 
 394:         if (isset($options['plugin'])) {
 395:             $name = Inflector::camelize($options['plugin']) . '.' . $name;
 396:         }
 397: 
 398:         if (!isset($options['callbacks'])) {
 399:             $options['callbacks'] = false;
 400:         }
 401: 
 402:         if (isset($options['cache'])) {
 403:             $contents = $this->_elementCache($name, $data, $options);
 404:             if ($contents !== false) {
 405:                 return $contents;
 406:             }
 407:         }
 408: 
 409:         $file = $this->_getElementFilename($name);
 410:         if ($file) {
 411:             return $this->_renderElement($file, $data, $options);
 412:         }
 413: 
 414:         if (empty($options['ignoreMissing'])) {
 415:             list ($plugin, $name) = pluginSplit($name, true);
 416:             $name = str_replace('/', DS, $name);
 417:             $file = $plugin . 'Elements' . DS . $name . $this->ext;
 418:             trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
 419:         }
 420:     }
 421: 
 422: /**
 423:  * Checks if an element exists
 424:  *
 425:  * @param string $name Name of template file in the /app/View/Elements/ folder,
 426:  *   or `MyPlugin.template` to check the template element from MyPlugin. If the element
 427:  *   is not found in the plugin, the normal view path cascade will be searched.
 428:  * @return boolean Success
 429:  */
 430:     public function elementExists($name) {
 431:         return (bool)$this->_getElementFilename($name);
 432:     }
 433: 
 434: /**
 435:  * Renders view for given view file and layout.
 436:  *
 437:  * Render triggers helper callbacks, which are fired before and after the view are rendered,
 438:  * as well as before and after the layout. The helper callbacks are called:
 439:  *
 440:  * - `beforeRender`
 441:  * - `afterRender`
 442:  * - `beforeLayout`
 443:  * - `afterLayout`
 444:  *
 445:  * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
 446:  *
 447:  * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
 448:  * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
 449:  * the view will be located along the regular view path cascade.
 450:  *
 451:  * @param string $view Name of view file to use
 452:  * @param string $layout Layout to use.
 453:  * @return string|null Rendered content or null if content already rendered and returned earlier.
 454:  * @throws CakeException If there is an error in the view.
 455:  */
 456:     public function render($view = null, $layout = null) {
 457:         if ($this->hasRendered) {
 458:             return;
 459:         }
 460:         $this->Blocks->set('content', '');
 461: 
 462:         if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
 463:             $this->_currentType = self::TYPE_VIEW;
 464:             $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
 465:             $this->Blocks->set('content', $this->_render($viewFileName));
 466:             $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
 467:         }
 468: 
 469:         if ($layout === null) {
 470:             $layout = $this->layout;
 471:         }
 472:         if ($layout && $this->autoLayout) {
 473:             $this->Blocks->set('content', $this->renderLayout('', $layout));
 474:         }
 475:         $this->hasRendered = true;
 476:         return $this->Blocks->get('content');
 477:     }
 478: 
 479: /**
 480:  * Renders a layout. Returns output from _render(). Returns false on error.
 481:  * Several variables are created for use in layout.
 482:  *
 483:  * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
 484:  * - `content_for_layout` - contains rendered view file
 485:  * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
 486:  *   the 'meta', 'css', and 'script' blocks. They are appended in that order.
 487:  *
 488:  * Deprecated features:
 489:  *
 490:  * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
 491:  *   Use the block features instead. `meta`, `css` and `script` will be populated
 492:  *   by the matching methods on HtmlHelper.
 493:  * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
 494:  * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
 495:  *   Use the `content` block instead.
 496:  *
 497:  * @param string $content Content to render in a view, wrapped by the surrounding layout.
 498:  * @param string $layout Layout name
 499:  * @return mixed Rendered output, or false on error
 500:  * @throws CakeException if there is an error in the view.
 501:  */
 502:     public function renderLayout($content, $layout = null) {
 503:         $layoutFileName = $this->_getLayoutFileName($layout);
 504:         if (empty($layoutFileName)) {
 505:             return $this->Blocks->get('content');
 506:         }
 507: 
 508:         if (empty($content)) {
 509:             $content = $this->Blocks->get('content');
 510:         } else {
 511:             $this->Blocks->set('content', $content);
 512:         }
 513:         $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
 514: 
 515:         $scripts = implode("\n\t", $this->_scripts);
 516:         $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
 517: 
 518:         $this->viewVars = array_merge($this->viewVars, array(
 519:             'content_for_layout' => $content,
 520:             'scripts_for_layout' => $scripts,
 521:         ));
 522: 
 523:         if (!isset($this->viewVars['title_for_layout'])) {
 524:             $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
 525:         }
 526: 
 527:         $this->_currentType = self::TYPE_LAYOUT;
 528:         $this->Blocks->set('content', $this->_render($layoutFileName));
 529: 
 530:         $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
 531:         return $this->Blocks->get('content');
 532:     }
 533: 
 534: /**
 535:  * Render cached view. Works in concert with CacheHelper and Dispatcher to
 536:  * render cached view files.
 537:  *
 538:  * @param string $filename the cache file to include
 539:  * @param string $timeStart the page render start time
 540:  * @return boolean Success of rendering the cached file.
 541:  */
 542:     public function renderCache($filename, $timeStart) {
 543:         $response = $this->response;
 544:         ob_start();
 545:         include $filename;
 546: 
 547:         $type = $response->mapType($response->type());
 548:         if (Configure::read('debug') > 0 && $type === 'html') {
 549:             echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
 550:         }
 551:         $out = ob_get_clean();
 552: 
 553:         if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
 554:             if (time() >= $match['1']) {
 555:                 //@codingStandardsIgnoreStart
 556:                 @unlink($filename);
 557:                 //@codingStandardsIgnoreEnd
 558:                 unset($out);
 559:                 return false;
 560:             }
 561:             return substr($out, strlen($match[0]));
 562:         }
 563:     }
 564: 
 565: /**
 566:  * Returns a list of variables available in the current View context
 567:  *
 568:  * @return array Array of the set view variable names.
 569:  */
 570:     public function getVars() {
 571:         return array_keys($this->viewVars);
 572:     }
 573: 
 574: /**
 575:  * Returns the contents of the given View variable(s)
 576:  *
 577:  * @param string $var The view var you want the contents of.
 578:  * @return mixed The content of the named var if its set, otherwise null.
 579:  * @deprecated Will be removed in 3.0. Use View::get() instead.
 580:  */
 581:     public function getVar($var) {
 582:         return $this->get($var);
 583:     }
 584: 
 585: /**
 586:  * Returns the contents of the given View variable or a block.
 587:  * Blocks are checked before view variables.
 588:  *
 589:  * @param string $var The view var you want the contents of.
 590:  * @return mixed The content of the named var if its set, otherwise null.
 591:  */
 592:     public function get($var) {
 593:         if (!isset($this->viewVars[$var])) {
 594:             return null;
 595:         }
 596:         return $this->viewVars[$var];
 597:     }
 598: 
 599: /**
 600:  * Get the names of all the existing blocks.
 601:  *
 602:  * @return array An array containing the blocks.
 603:  * @see ViewBlock::keys()
 604:  */
 605:     public function blocks() {
 606:         return $this->Blocks->keys();
 607:     }
 608: 
 609: /**
 610:  * Start capturing output for a 'block'
 611:  *
 612:  * @param string $name The name of the block to capture for.
 613:  * @return void
 614:  * @see ViewBlock::start()
 615:  */
 616:     public function start($name) {
 617:         $this->Blocks->start($name);
 618:     }
 619: 
 620: /**
 621:  * Start capturing output for a 'block' if it has no content
 622:  *
 623:  * @param string $name The name of the block to capture for.
 624:  * @return void
 625:  * @see ViewBlock::startIfEmpty()
 626:  */
 627:     public function startIfEmpty($name) {
 628:         $this->Blocks->startIfEmpty($name);
 629:     }
 630: 
 631: /**
 632:  * Append to an existing or new block. Appending to a new
 633:  * block will create the block.
 634:  *
 635:  * @param string $name Name of the block
 636:  * @param mixed $value The content for the block.
 637:  * @return void
 638:  * @see ViewBlock::concat()
 639:  */
 640:     public function append($name, $value = null) {
 641:         $this->Blocks->concat($name, $value);
 642:     }
 643: 
 644: /**
 645:  * Prepend to an existing or new block. Prepending to a new
 646:  * block will create the block.
 647:  *
 648:  * @param string $name Name of the block
 649:  * @param mixed $value The content for the block.
 650:  * @return void
 651:  * @see ViewBlock::concat()
 652:  */
 653:     public function prepend($name, $value = null) {
 654:         $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
 655:     }
 656: 
 657: /**
 658:  * Set the content for a block. This will overwrite any
 659:  * existing content.
 660:  *
 661:  * @param string $name Name of the block
 662:  * @param mixed $value The content for the block.
 663:  * @return void
 664:  * @see ViewBlock::set()
 665:  */
 666:     public function assign($name, $value) {
 667:         $this->Blocks->set($name, $value);
 668:     }
 669: 
 670: /**
 671:  * Fetch the content for a block. If a block is
 672:  * empty or undefined '' will be returned.
 673:  *
 674:  * @param string $name Name of the block
 675:  * @param string $default Default text
 676:  * @return string $default The block content or $default if the block does not exist.
 677:  * @see ViewBlock::get()
 678:  */
 679:     public function fetch($name, $default = '') {
 680:         return $this->Blocks->get($name, $default);
 681:     }
 682: 
 683: /**
 684:  * End a capturing block. The compliment to View::start()
 685:  *
 686:  * @return void
 687:  * @see ViewBlock::end()
 688:  */
 689:     public function end() {
 690:         $this->Blocks->end();
 691:     }
 692: 
 693: /**
 694:  * Provides view or element extension/inheritance. Views can extends a
 695:  * parent view and populate blocks in the parent template.
 696:  *
 697:  * @param string $name The view or element to 'extend' the current one with.
 698:  * @return void
 699:  * @throws LogicException when you extend a view with itself or make extend loops.
 700:  * @throws LogicException when you extend an element which doesn't exist
 701:  */
 702:     public function extend($name) {
 703:         if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
 704:             $parent = $this->_getViewFileName($name);
 705:         } else {
 706:             switch ($this->_currentType) {
 707:                 case self::TYPE_ELEMENT:
 708:                     $parent = $this->_getElementFileName($name);
 709:                     if (!$parent) {
 710:                         list($plugin, $name) = $this->pluginSplit($name);
 711:                         $paths = $this->_paths($plugin);
 712:                         $defaultPath = $paths[0] . 'Elements' . DS;
 713:                         throw new LogicException(__d(
 714:                             'cake_dev',
 715:                             'You cannot extend an element which does not exist (%s).',
 716:                             $defaultPath . $name . $this->ext
 717:                         ));
 718:                     }
 719:                     break;
 720:                 case self::TYPE_LAYOUT:
 721:                     $parent = $this->_getLayoutFileName($name);
 722:                     break;
 723:                 default:
 724:                     $parent = $this->_getViewFileName($name);
 725:             }
 726:         }
 727: 
 728:         if ($parent == $this->_current) {
 729:             throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
 730:         }
 731:         if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
 732:             throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
 733:         }
 734:         $this->_parents[$this->_current] = $parent;
 735:     }
 736: 
 737: /**
 738:  * Adds a script block or other element to be inserted in $scripts_for_layout in
 739:  * the `<head />` of a document layout
 740:  *
 741:  * @param string $name Either the key name for the script, or the script content. Name can be used to
 742:  *   update/replace a script element.
 743:  * @param string $content The content of the script being added, optional.
 744:  * @return void
 745:  * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
 746:  * @see View::start()
 747:  */
 748:     public function addScript($name, $content = null) {
 749:         if (empty($content)) {
 750:             if (!in_array($name, array_values($this->_scripts))) {
 751:                 $this->_scripts[] = $name;
 752:             }
 753:         } else {
 754:             $this->_scripts[$name] = $content;
 755:         }
 756:     }
 757: 
 758: /**
 759:  * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
 760:  *
 761:  * @param string $object Type of object, i.e. 'form' or 'link'
 762:  * @param string $url The object's target URL
 763:  * @return string
 764:  */
 765:     public function uuid($object, $url) {
 766:         $c = 1;
 767:         $url = Router::url($url);
 768:         $hash = $object . substr(md5($object . $url), 0, 10);
 769:         while (in_array($hash, $this->uuids)) {
 770:             $hash = $object . substr(md5($object . $url . $c), 0, 10);
 771:             $c++;
 772:         }
 773:         $this->uuids[] = $hash;
 774:         return $hash;
 775:     }
 776: 
 777: /**
 778:  * Allows a template or element to set a variable that will be available in
 779:  * a layout or other element. Analogous to Controller::set().
 780:  *
 781:  * @param string|array $one A string or an array of data.
 782:  * @param string|array $two Value in case $one is a string (which then works as the key).
 783:  *    Unused if $one is an associative array, otherwise serves as the values to $one's keys.
 784:  * @return void
 785:  */
 786:     public function set($one, $two = null) {
 787:         $data = null;
 788:         if (is_array($one)) {
 789:             if (is_array($two)) {
 790:                 $data = array_combine($one, $two);
 791:             } else {
 792:                 $data = $one;
 793:             }
 794:         } else {
 795:             $data = array($one => $two);
 796:         }
 797:         if (!$data) {
 798:             return false;
 799:         }
 800:         $this->viewVars = $data + $this->viewVars;
 801:     }
 802: 
 803: /**
 804:  * Magic accessor for helpers. Provides access to attributes that were deprecated.
 805:  *
 806:  * @param string $name Name of the attribute to get.
 807:  * @return mixed
 808:  */
 809:     public function __get($name) {
 810:         switch ($name) {
 811:             case 'base':
 812:             case 'here':
 813:             case 'webroot':
 814:             case 'data':
 815:                 return $this->request->{$name};
 816:             case 'action':
 817:                 return $this->request->params['action'];
 818:             case 'params':
 819:                 return $this->request;
 820:             case 'output':
 821:                 return $this->Blocks->get('content');
 822:         }
 823:         if (isset($this->Helpers->{$name})) {
 824:             $this->{$name} = $this->Helpers->{$name};
 825:             return $this->Helpers->{$name};
 826:         }
 827:         return $this->{$name};
 828:     }
 829: 
 830: /**
 831:  * Magic accessor for deprecated attributes.
 832:  *
 833:  * @param string $name Name of the attribute to set.
 834:  * @param mixed $value Value of the attribute to set.
 835:  * @return mixed
 836:  */
 837:     public function __set($name, $value) {
 838:         switch ($name) {
 839:             case 'output':
 840:                 return $this->Blocks->set('content', $value);
 841:             default:
 842:                 $this->{$name} = $value;
 843:         }
 844:     }
 845: 
 846: /**
 847:  * Magic isset check for deprecated attributes.
 848:  *
 849:  * @param string $name Name of the attribute to check.
 850:  * @return boolean
 851:  */
 852:     public function __isset($name) {
 853:         if (isset($this->{$name})) {
 854:             return true;
 855:         }
 856:         $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
 857:         if (in_array($name, $magicGet)) {
 858:             return $this->__get($name) !== null;
 859:         }
 860:         return false;
 861:     }
 862: 
 863: /**
 864:  * Interact with the HelperCollection to load all the helpers.
 865:  *
 866:  * @return void
 867:  */
 868:     public function loadHelpers() {
 869:         $helpers = HelperCollection::normalizeObjectArray($this->helpers);
 870:         foreach ($helpers as $properties) {
 871:             list(, $class) = pluginSplit($properties['class']);
 872:             $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
 873:         }
 874:     }
 875: 
 876: /**
 877:  * Renders and returns output for given view filename with its
 878:  * array of data. Handles parent/extended views.
 879:  *
 880:  * @param string $viewFile Filename of the view
 881:  * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
 882:  * @return string Rendered output
 883:  * @throws CakeException when a block is left open.
 884:  */
 885:     protected function _render($viewFile, $data = array()) {
 886:         if (empty($data)) {
 887:             $data = $this->viewVars;
 888:         }
 889:         $this->_current = $viewFile;
 890:         $initialBlocks = count($this->Blocks->unclosed());
 891: 
 892:         $eventManager = $this->getEventManager();
 893:         $beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
 894: 
 895:         $eventManager->dispatch($beforeEvent);
 896:         $content = $this->_evaluate($viewFile, $data);
 897: 
 898:         $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
 899: 
 900:         $afterEvent->modParams = 1;
 901:         $eventManager->dispatch($afterEvent);
 902:         $content = $afterEvent->data[1];
 903: 
 904:         if (isset($this->_parents[$viewFile])) {
 905:             $this->_stack[] = $this->fetch('content');
 906:             $this->assign('content', $content);
 907: 
 908:             $content = $this->_render($this->_parents[$viewFile]);
 909:             $this->assign('content', array_pop($this->_stack));
 910:         }
 911: 
 912:         $remainingBlocks = count($this->Blocks->unclosed());
 913: 
 914:         if ($initialBlocks !== $remainingBlocks) {
 915:             throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
 916:         }
 917: 
 918:         return $content;
 919:     }
 920: 
 921: /**
 922:  * Sandbox method to evaluate a template / view script in.
 923:  *
 924:  * @param string $viewFn Filename of the view
 925:  * @param array $dataForView Data to include in rendered view.
 926:  *    If empty the current View::$viewVars will be used.
 927:  * @return string Rendered output
 928:  */
 929:     protected function _evaluate($viewFile, $dataForView) {
 930:         $this->__viewFile = $viewFile;
 931:         extract($dataForView);
 932:         ob_start();
 933: 
 934:         include $this->__viewFile;
 935: 
 936:         unset($this->__viewFile);
 937:         return ob_get_clean();
 938:     }
 939: 
 940: /**
 941:  * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
 942:  *
 943:  * @param string $helperName Name of the helper to load.
 944:  * @param array $settings Settings for the helper
 945:  * @return Helper a constructed helper object.
 946:  * @see HelperCollection::load()
 947:  */
 948:     public function loadHelper($helperName, $settings = array()) {
 949:         return $this->Helpers->load($helperName, $settings);
 950:     }
 951: 
 952: /**
 953:  * Returns filename of given action's template file (.ctp) as a string.
 954:  * CamelCased action names will be under_scored! This means that you can have
 955:  * LongActionNames that refer to long_action_names.ctp views.
 956:  *
 957:  * @param string $name Controller action to find template filename for
 958:  * @return string Template filename
 959:  * @throws MissingViewException when a view file could not be found.
 960:  */
 961:     protected function _getViewFileName($name = null) {
 962:         $subDir = null;
 963: 
 964:         if ($this->subDir !== null) {
 965:             $subDir = $this->subDir . DS;
 966:         }
 967: 
 968:         if ($name === null) {
 969:             $name = $this->view;
 970:         }
 971:         $name = str_replace('/', DS, $name);
 972:         list($plugin, $name) = $this->pluginSplit($name);
 973: 
 974:         if (strpos($name, DS) === false && $name[0] !== '.') {
 975:             $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
 976:         } elseif (strpos($name, DS) !== false) {
 977:             if ($name[0] === DS || $name[1] === ':') {
 978:                 if (is_file($name)) {
 979:                     return $name;
 980:                 }
 981:                 $name = trim($name, DS);
 982:             } elseif ($name[0] === '.') {
 983:                 $name = substr($name, 3);
 984:             } elseif (!$plugin || $this->viewPath !== $this->name) {
 985:                 $name = $this->viewPath . DS . $subDir . $name;
 986:             }
 987:         }
 988:         $paths = $this->_paths($plugin);
 989:         $exts = $this->_getExtensions();
 990:         foreach ($exts as $ext) {
 991:             foreach ($paths as $path) {
 992:                 if (file_exists($path . $name . $ext)) {
 993:                     return $path . $name . $ext;
 994:                 }
 995:             }
 996:         }
 997:         $defaultPath = $paths[0];
 998: 
 999:         if ($this->plugin) {
1000:             $pluginPaths = App::path('plugins');
1001:             foreach ($paths as $path) {
1002:                 if (strpos($path, $pluginPaths[0]) === 0) {
1003:                     $defaultPath = $path;
1004:                     break;
1005:                 }
1006:             }
1007:         }
1008:         throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
1009:     }
1010: 
1011: /**
1012:  * Splits a dot syntax plugin name into its plugin and filename.
1013:  * If $name does not have a dot, then index 0 will be null.
1014:  * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
1015:  *
1016:  * @param string $name The name you want to plugin split.
1017:  * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
1018:  * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
1019:  */
1020:     public function pluginSplit($name, $fallback = true) {
1021:         $plugin = null;
1022:         list($first, $second) = pluginSplit($name);
1023:         if (CakePlugin::loaded($first) === true) {
1024:             $name = $second;
1025:             $plugin = $first;
1026:         }
1027:         if (isset($this->plugin) && !$plugin && $fallback) {
1028:             $plugin = $this->plugin;
1029:         }
1030:         return array($plugin, $name);
1031:     }
1032: 
1033: /**
1034:  * Returns layout filename for this template as a string.
1035:  *
1036:  * @param string $name The name of the layout to find.
1037:  * @return string Filename for layout file (.ctp).
1038:  * @throws MissingLayoutException when a layout cannot be located
1039:  */
1040:     protected function _getLayoutFileName($name = null) {
1041:         if ($name === null) {
1042:             $name = $this->layout;
1043:         }
1044:         $subDir = null;
1045: 
1046:         if ($this->layoutPath !== null) {
1047:             $subDir = $this->layoutPath . DS;
1048:         }
1049:         list($plugin, $name) = $this->pluginSplit($name);
1050:         $paths = $this->_paths($plugin);
1051:         $file = 'Layouts' . DS . $subDir . $name;
1052: 
1053:         $exts = $this->_getExtensions();
1054:         foreach ($exts as $ext) {
1055:             foreach ($paths as $path) {
1056:                 if (file_exists($path . $file . $ext)) {
1057:                     return $path . $file . $ext;
1058:                 }
1059:             }
1060:         }
1061:         throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
1062:     }
1063: 
1064: /**
1065:  * Get the extensions that view files can use.
1066:  *
1067:  * @return array Array of extensions view files use.
1068:  */
1069:     protected function _getExtensions() {
1070:         $exts = array($this->ext);
1071:         if ($this->ext !== '.ctp') {
1072:             $exts[] = '.ctp';
1073:         }
1074:         return $exts;
1075:     }
1076: 
1077: /**
1078:  * Finds an element filename, returns false on failure.
1079:  *
1080:  * @param string $name The name of the element to find.
1081:  * @return mixed Either a string to the element filename or false when one can't be found.
1082:  */
1083:     protected function _getElementFileName($name) {
1084:         list($plugin, $name) = $this->pluginSplit($name);
1085: 
1086:         $paths = $this->_paths($plugin);
1087:         $exts = $this->_getExtensions();
1088:         foreach ($exts as $ext) {
1089:             foreach ($paths as $path) {
1090:                 if (file_exists($path . 'Elements' . DS . $name . $ext)) {
1091:                     return $path . 'Elements' . DS . $name . $ext;
1092:                 }
1093:             }
1094:         }
1095:         return false;
1096:     }
1097: 
1098: /**
1099:  * Return all possible paths to find view files in order
1100:  *
1101:  * @param string $plugin Optional plugin name to scan for view files.
1102:  * @param boolean $cached Set to false to force a refresh of view paths. Default true.
1103:  * @return array paths
1104:  */
1105:     protected function _paths($plugin = null, $cached = true) {
1106:         if ($plugin === null && $cached === true && !empty($this->_paths)) {
1107:             return $this->_paths;
1108:         }
1109:         $paths = array();
1110:         $viewPaths = App::path('View');
1111:         $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
1112: 
1113:         if (!empty($plugin)) {
1114:             $count = count($viewPaths);
1115:             for ($i = 0; $i < $count; $i++) {
1116:                 if (!in_array($viewPaths[$i], $corePaths)) {
1117:                     $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
1118:                 }
1119:             }
1120:             $paths = array_merge($paths, App::path('View', $plugin));
1121:         }
1122: 
1123:         $paths = array_unique(array_merge($paths, $viewPaths));
1124:         if (!empty($this->theme)) {
1125:             $theme = Inflector::camelize($this->theme);
1126:             $themePaths = array();
1127:             foreach ($paths as $path) {
1128:                 if (strpos($path, DS . 'Plugin' . DS) === false) {
1129:                     if ($plugin) {
1130:                         $themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
1131:                     }
1132:                     $themePaths[] = $path . 'Themed' . DS . $theme . DS;
1133:                 }
1134:             }
1135:             $paths = array_merge($themePaths, $paths);
1136:         }
1137:         $paths = array_merge($paths, $corePaths);
1138:         if ($plugin !== null) {
1139:             return $paths;
1140:         }
1141:         return $this->_paths = $paths;
1142:     }
1143: 
1144: /**
1145:  * Checks if an element is cached and returns the cached data if present
1146:  *
1147:  * @param string $name Element name
1148:  * @param string $data Data
1149:  * @param array $options Element options
1150:  * @return string|null
1151:  */
1152:     protected function _elementCache($name, $data, $options) {
1153:         $plugin = null;
1154:         list($plugin, $name) = $this->pluginSplit($name);
1155: 
1156:         $underscored = null;
1157:         if ($plugin) {
1158:             $underscored = Inflector::underscore($plugin);
1159:         }
1160:         $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
1161:         $this->elementCacheSettings = array(
1162:             'config' => $this->elementCache,
1163:             'key' => implode('_', $keys)
1164:         );
1165:         if (is_array($options['cache'])) {
1166:             $defaults = array(
1167:                 'config' => $this->elementCache,
1168:                 'key' => $this->elementCacheSettings['key']
1169:             );
1170:             $this->elementCacheSettings = array_merge($defaults, $options['cache']);
1171:         }
1172:         $this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
1173:         return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
1174:     }
1175: 
1176: /**
1177:  * Renders an element and fires the before and afterRender callbacks for it
1178:  * and writes to the cache if a cache is used
1179:  *
1180:  * @param string $file Element file path
1181:  * @param array $data Data to render
1182:  * @param array $options Element options
1183:  * @return string
1184:  */
1185:     protected function _renderElement($file, $data, $options) {
1186:         if ($options['callbacks']) {
1187:             $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
1188:         }
1189: 
1190:         $current = $this->_current;
1191:         $restore = $this->_currentType;
1192: 
1193:         $this->_currentType = self::TYPE_ELEMENT;
1194:         $element = $this->_render($file, array_merge($this->viewVars, $data));
1195: 
1196:         $this->_currentType = $restore;
1197:         $this->_current = $current;
1198: 
1199:         if ($options['callbacks']) {
1200:             $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
1201:         }
1202:         if (isset($options['cache'])) {
1203:             Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
1204:         }
1205:         return $element;
1206:     }
1207: }
1208: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs