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.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 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
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AppController
  • CakeErrorController
  • Component
  • ComponentCollection
  • Controller
  • PagesController
  • Scaffold
   1: <?php
   2: /**
   3:  * Base controller class.
   4:  *
   5:  * PHP 5
   6:  *
   7:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
   8:  * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
   9:  *
  10:  * Licensed under The MIT License
  11:  * Redistributions of files must retain the above copyright notice.
  12:  *
  13:  * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14:  * @link          http://cakephp.org CakePHP(tm) Project
  15:  * @package       Cake.Controller
  16:  * @since         CakePHP(tm) v 0.2.9
  17:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
  18:  */
  19: 
  20: /**
  21:  * Include files
  22:  */
  23: App::uses('CakeResponse', 'Network');
  24: App::uses('ClassRegistry', 'Utility');
  25: App::uses('ComponentCollection', 'Controller');
  26: App::uses('View', 'View');
  27: 
  28: /**
  29:  * Application controller class for organization of business logic.
  30:  * Provides basic functionality, such as rendering views inside layouts,
  31:  * automatic model availability, redirection, callbacks, and more.
  32:  *
  33:  * Controllers should provide a number of 'action' methods.  These are public methods on the controller
  34:  * that are not prefixed with a '_' and not part of Controller.  Each action serves as an endpoint for
  35:  * performing a specific action on a resource or collection of resources.  For example adding or editing a new
  36:  * object, or listing a set of objects.
  37:  *
  38:  * You can access request parameters, using `$this->request`.  The request object contains all the POST, GET and FILES
  39:  * that were part of the request.
  40:  *
  41:  * After performing the required actions, controllers are responsible for creating a response.  This usually
  42:  * takes the form of a generated View, or possibly a redirection to another controller action.  In either case
  43:  * `$this->response` allows you to manipulate all aspects of the response.
  44:  *
  45:  * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
  46:  * use conventional names.  For example `/posts/index` maps to `PostsController::index()`.  You can re-map urls
  47:  * using Router::connect().
  48:  *
  49:  * @package       Cake.Controller
  50:  * @property      AclComponent $Acl
  51:  * @property      AuthComponent $Auth
  52:  * @property      CookieComponent $Cookie
  53:  * @property      EmailComponent $Email
  54:  * @property      PaginatorComponent $Paginator
  55:  * @property      RequestHandlerComponent $RequestHandler
  56:  * @property      SecurityComponent $Security
  57:  * @property      SessionComponent $Session
  58:  * @link          http://book.cakephp.org/2.0/en/controllers.html
  59:  */
  60: class Controller extends Object {
  61: 
  62: /**
  63:  * The name of this controller. Controller names are plural, named after the model they manipulate.
  64:  *
  65:  * @var string
  66:  * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes
  67:  */
  68:     public $name = null;
  69: 
  70: /**
  71:  * An array containing the class names of models this controller uses.
  72:  *
  73:  * Example: `public $uses = array('Product', 'Post', 'Comment');`
  74:  *
  75:  * Can be set to array() to use no models.  Can be set to false to
  76:  * use no models and prevent the merging of $uses with AppController
  77:  *
  78:  * @var mixed A single name as a string or a list of names as an array.
  79:  * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  80:  */
  81:     public $uses = false;
  82: 
  83: /**
  84:  * An array containing the names of helpers this controller uses. The array elements should
  85:  * not contain the "Helper" part of the classname.
  86:  *
  87:  * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
  88:  *
  89:  * @var mixed A single name as a string or a list of names as an array.
  90:  * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  91:  */
  92:     public $helpers = array('Session', 'Html', 'Form');
  93: 
  94: /**
  95:  * An instance of a CakeRequest object that contains information about the current request.
  96:  * This object contains all the information about a request and several methods for reading
  97:  * additional information about the request.
  98:  *
  99:  * @var CakeRequest
 100:  */
 101:     public $request;
 102: 
 103: /**
 104:  * An instance of a CakeResponse object that contains information about the impending response
 105:  *
 106:  * @var CakeResponse
 107:  */
 108:     public $response;
 109: 
 110: /**
 111:  * The classname to use for creating the response object.
 112:  *
 113:  * @var string
 114:  */
 115:     protected $_responseClass = 'CakeResponse';
 116: 
 117: /**
 118:  * The name of the views subfolder containing views for this controller.
 119:  *
 120:  * @var string
 121:  */
 122:     public $viewPath = null;
 123: 
 124: /**
 125:  * The name of the layouts subfolder containing layouts for this controller.
 126:  *
 127:  * @var string
 128:  */
 129:     public $layoutPath = null;
 130: 
 131: /**
 132:  * Contains variables to be handed to the view.
 133:  *
 134:  * @var array
 135:  */
 136:     public $viewVars = array();
 137: 
 138: 
 139: /**
 140:  * The name of the view file to render. The name specified
 141:  * is the filename in /app/View/<SubFolder> without the .ctp extension.
 142:  *
 143:  * @var string
 144:  */
 145:     public $view = null;
 146: 
 147: /**
 148:  * The name of the layout file to render the view inside of. The name specified
 149:  * is the filename of the layout in /app/View/Layouts without the .ctp
 150:  * extension.
 151:  *
 152:  * @var string
 153:  */
 154:     public $layout = 'default';
 155: 
 156: /**
 157:  * Set to true to automatically render the view
 158:  * after action logic.
 159:  *
 160:  * @var boolean
 161:  */
 162:     public $autoRender = true;
 163: 
 164: /**
 165:  * Set to true to automatically render the layout around views.
 166:  *
 167:  * @var boolean
 168:  */
 169:     public $autoLayout = true;
 170: 
 171: /**
 172:  * Instance of ComponentCollection used to handle callbacks.
 173:  *
 174:  * @var ComponentCollection
 175:  */
 176:     public $Components = null;
 177: 
 178: /**
 179:  * Array containing the names of components this controller uses. Component names
 180:  * should not contain the "Component" portion of the classname.
 181:  *
 182:  * Example: `public $components = array('Session', 'RequestHandler', 'Acl');`
 183:  *
 184:  * @var array
 185:  * @link http://book.cakephp.org/view/961/components-helpers-and-uses
 186:  */
 187:     public $components = array('Session');
 188: 
 189: /**
 190:  * The name of the View class this controller sends output to.
 191:  *
 192:  * @var string
 193:  */
 194:     public $viewClass = 'View';
 195: 
 196: /**
 197:  * Instance of the View created during rendering. Won't be set until after Controller::render() is called.
 198:  *
 199:  * @var View
 200:  */
 201:     public $View;
 202: 
 203: /**
 204:  * File extension for view templates. Defaults to Cake's conventional ".ctp".
 205:  *
 206:  * @var string
 207:  */
 208:     public $ext = '.ctp';
 209: 
 210: /**
 211:  * Automatically set to the name of a plugin.
 212:  *
 213:  * @var string
 214:  */
 215:     public $plugin = null;
 216: 
 217: /**
 218:  * Used to define methods a controller that will be cached. To cache a
 219:  * single action, the value is set to an array containing keys that match
 220:  * action names and values that denote cache expiration times (in seconds).
 221:  *
 222:  * Example:
 223:  *
 224:  * {{{
 225:  * public $cacheAction = array(
 226:  *      'view/23/' => 21600,
 227:  *      'recalled/' => 86400
 228:  *  );
 229:  * }}}
 230:  *
 231:  * $cacheAction can also be set to a strtotime() compatible string. This
 232:  * marks all the actions in the controller for view caching.
 233:  *
 234:  * @var mixed
 235:  * @link http://book.cakephp.org/view/1380/Caching-in-the-Controller
 236:  */
 237:     public $cacheAction = false;
 238: 
 239: /**
 240:  * Holds all params passed and named.
 241:  *
 242:  * @var mixed
 243:  */
 244:     public $passedArgs = array();
 245: 
 246: /**
 247:  * Triggers Scaffolding
 248:  *
 249:  * @var mixed
 250:  * @link http://book.cakephp.org/view/1103/Scaffolding
 251:  */
 252:     public $scaffold = false;
 253: 
 254: /**
 255:  * Holds current methods of the controller.  This is a list of all the methods reachable
 256:  * via url.  Modifying this array, will allow you to change which methods can be reached.
 257:  *
 258:  * @var array
 259:  */
 260:     public $methods = array();
 261: 
 262: /**
 263:  * This controller's primary model class name, the Inflector::classify()'ed version of
 264:  * the controller's $name property.
 265:  *
 266:  * Example: For a controller named 'Comments', the modelClass would be 'Comment'
 267:  *
 268:  * @var string
 269:  */
 270:     public $modelClass = null;
 271: 
 272: /**
 273:  * This controller's model key name, an underscored version of the controller's $modelClass property.
 274:  *
 275:  * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
 276:  *
 277:  * @var string
 278:  */
 279:     public $modelKey = null;
 280: 
 281: /**
 282:  * Holds any validation errors produced by the last call of the validateErrors() method/
 283:  *
 284:  * @var array Validation errors, or false if none
 285:  */
 286:     public $validationErrors = null;
 287: 
 288: /**
 289:  * The class name of the parent class you wish to merge with.
 290:  * Typically this is AppController, but you may wish to merge vars with a different
 291:  * parent class.
 292:  *
 293:  * @var string
 294:  */
 295:     protected $_mergeParent = 'AppController';
 296: 
 297: /**
 298:  * Constructor.
 299:  *
 300:  * @param CakeRequest $request Request object for this controller. Can be null for testing,
 301:  *  but expect that features that use the request parameters will not work.
 302:  * @param CakeResponse $response Response object for this controller.
 303:  */
 304:     public function __construct($request = null, $response = null) {
 305:         if ($this->name === null) {
 306:             $this->name = substr(get_class($this), 0, strlen(get_class($this)) -10);
 307:         }
 308: 
 309:         if ($this->viewPath == null) {
 310:             $this->viewPath = $this->name;
 311:         }
 312: 
 313:         $this->modelClass = Inflector::singularize($this->name);
 314:         $this->modelKey = Inflector::underscore($this->modelClass);
 315:         $this->Components = new ComponentCollection();
 316: 
 317:         $childMethods = get_class_methods($this);
 318:         $parentMethods = get_class_methods('Controller');
 319: 
 320:         $this->methods = array_diff($childMethods, $parentMethods);
 321: 
 322:         if ($request instanceof CakeRequest) {
 323:             $this->setRequest($request);
 324:         }
 325:         if ($response instanceof CakeResponse) {
 326:             $this->response = $response;
 327:         }
 328:         parent::__construct();
 329:     }
 330: 
 331: /**
 332:  * Provides backwards compatibility to avoid problems with empty and isset to alias properties.
 333:  * Lazy loads models using the loadModel() method if declared in $uses
 334:  *
 335:  * @param string $name
 336:  * @return void
 337:  */
 338:     public function __isset($name) {
 339:         switch ($name) {
 340:             case 'base':
 341:             case 'here':
 342:             case 'webroot':
 343:             case 'data':
 344:             case 'action':
 345:             case 'params':
 346:                 return true;
 347:         }
 348: 
 349:         if (is_array($this->uses)) {
 350:             foreach ($this->uses as $modelClass) {
 351:                 list($plugin, $class) = pluginSplit($modelClass, true);
 352:                 if ($name === $class) {
 353:                     if (!$plugin) {
 354:                         $plugin = $this->plugin ? $this->plugin . '.' : null;
 355:                     }
 356:                     return $this->loadModel($modelClass);
 357:                 }
 358:             }
 359:         }
 360: 
 361:         if ($name === $this->modelClass) {
 362:             list($plugin, $class) = pluginSplit($name, true);
 363:             if (!$plugin) {
 364:                 $plugin = $this->plugin ? $this->plugin . '.' : null;
 365:             }
 366:             return $this->loadModel($plugin . $this->modelClass);
 367:         }
 368: 
 369:         return false;
 370:     }
 371: 
 372: /**
 373:  * Provides backwards compatibility access to the request object properties.
 374:  * Also provides the params alias.
 375:  *
 376:  * @param string $name
 377:  * @return void
 378:  */
 379:     public function __get($name) {
 380:         switch ($name) {
 381:             case 'base':
 382:             case 'here':
 383:             case 'webroot':
 384:             case 'data':
 385:                 return $this->request->{$name};
 386:             case 'action':
 387:                 return isset($this->request->params['action']) ? $this->request->params['action'] : '';
 388:             case 'params':
 389:                 return $this->request;
 390:             case 'paginate':
 391:                 return $this->Components->load('Paginator')->settings;
 392:         }
 393: 
 394:         if (isset($this->{$name})) {
 395:             return $this->{$name};
 396:         }
 397: 
 398:         return null;
 399:     }
 400: 
 401: /**
 402:  * Provides backwards compatibility access for setting values to the request object.
 403:  *
 404:  * @param string $name
 405:  * @param mixed $value
 406:  * @return void
 407:  */
 408:     public function __set($name, $value) {
 409:         switch ($name) {
 410:             case 'base':
 411:             case 'here':
 412:             case 'webroot':
 413:             case 'data':
 414:                 return $this->request->{$name} = $value;
 415:             case 'action':
 416:                 return $this->request->params['action'] = $value;
 417:             case 'params':
 418:                 return $this->request->params = $value;
 419:             case 'paginate':
 420:                 return $this->Components->load('Paginator')->settings = $value;
 421:         }
 422:         return $this->{$name} = $value;
 423:     }
 424: 
 425: /**
 426:  * Sets the request objects and configures a number of controller properties
 427:  * based on the contents of the request.  The properties that get set are
 428:  *
 429:  * - $this->request - To the $request parameter
 430:  * - $this->plugin - To the $request->params['plugin']
 431:  * - $this->view - To the $request->params['action']
 432:  * - $this->autoLayout - To the false if $request->params['bare']; is set.
 433:  * - $this->autoRender - To false if $request->params['return'] == 1
 434:  * - $this->passedArgs - The the combined results of params['named'] and params['pass]
 435:  *
 436:  * @param CakeRequest $request
 437:  * @return void
 438:  */
 439:     public function setRequest(CakeRequest $request) {
 440:         $this->request = $request;
 441:         $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
 442:         $this->view = isset($request->params['action']) ? $request->params['action'] : null;
 443:         if (isset($request->params['pass']) && isset($request->params['named'])) {
 444:             $this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
 445:         }
 446: 
 447:         if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
 448:             $this->autoRender = false;
 449:         }
 450:         if (!empty($request->params['bare'])) {
 451:             $this->autoLayout = false;
 452:         }
 453:     }
 454: 
 455: /**
 456:  * Dispatches the controller action.  Checks that the action
 457:  * exists and isn't private.
 458:  *
 459:  * @param CakeRequest $request
 460:  * @return mixed The resulting response.
 461:  * @throws PrivateActionException, MissingActionException
 462:  */
 463:     public function invokeAction(CakeRequest $request) {
 464:         try {
 465:             $method = new ReflectionMethod($this, $request->params['action']);
 466: 
 467:             if ($this->_isPrivateAction($method, $request)) {
 468:                 throw new PrivateActionException(array(
 469:                     'controller' => $this->name . "Controller",
 470:                     'action' => $request->params['action']
 471:                 ));
 472:             }
 473:             return $method->invokeArgs($this, $request->params['pass']);
 474: 
 475:         } catch (ReflectionException $e) {
 476:             if ($this->scaffold !== false) {
 477:                 return $this->_getScaffold($request);
 478:             }
 479:             throw new MissingActionException(array(
 480:                 'controller' => $this->name . "Controller",
 481:                 'action' => $request->params['action']
 482:             ));
 483:         }
 484:     }
 485: 
 486: /**
 487:  * Check if the request's action is marked as private, with an underscore,
 488:  * or if the request is attempting to directly accessing a prefixed action.
 489:  *
 490:  * @param ReflectionMethod $method The method to be invoked.
 491:  * @param CakeRequest $request The request to check.
 492:  * @return boolean
 493:  */
 494:     protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
 495:         $privateAction = (
 496:             $method->name[0] === '_' ||
 497:             !$method->isPublic() ||
 498:             !in_array($method->name,  $this->methods)
 499:         );
 500:         $prefixes = Router::prefixes();
 501: 
 502:         if (!$privateAction && !empty($prefixes)) {
 503:             if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
 504:                 list($prefix) = explode('_', $request->params['action']);
 505:                 $privateAction = in_array($prefix, $prefixes);
 506:             }
 507:         }
 508:         return $privateAction;
 509:     }
 510: 
 511: /**
 512:  * Returns a scaffold object to use for dynamically scaffolded controllers.
 513:  *
 514:  * @param CakeRequest $request
 515:  * @return Scaffold
 516:  */
 517:     protected function _getScaffold(CakeRequest $request) {
 518:         return new Scaffold($this, $request);
 519:     }
 520: 
 521: /**
 522:  * Merge components, helpers, and uses vars from Controller::$_mergeParent and PluginAppController.
 523:  *
 524:  * @return void
 525:  */
 526:     protected function _mergeControllerVars() {
 527:         $pluginController = $pluginDot = null;
 528: 
 529:         if (!empty($this->plugin)) {
 530:             $pluginController = $this->plugin . 'AppController';
 531:             if (!is_subclass_of($this, $pluginController)) {
 532:                 $pluginController = null;
 533:             }
 534:             $pluginDot = $this->plugin . '.';
 535:         }
 536: 
 537:         if ($pluginController && $this->plugin != null) {
 538:             $merge = array('components', 'helpers');
 539:             $appVars = get_class_vars($pluginController);
 540:             if (
 541:                 ($this->uses !== null || $this->uses !== false) &&
 542:                 is_array($this->uses) && !empty($appVars['uses'])
 543:             ) {
 544:                 $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
 545:             }
 546:             $this->_mergeVars($merge, $pluginController);
 547:         }
 548: 
 549:         if (is_subclass_of($this, $this->_mergeParent) || !empty($pluginController)) {
 550:             $appVars = get_class_vars($this->_mergeParent);
 551:             $uses = $appVars['uses'];
 552:             $merge = array('components', 'helpers');
 553: 
 554:             if ($uses == $this->uses && !empty($this->uses)) {
 555:                 if (!in_array($pluginDot . $this->modelClass, $this->uses)) {
 556:                     array_unshift($this->uses, $pluginDot . $this->modelClass);
 557:                 } elseif ($this->uses[0] !== $pluginDot . $this->modelClass) {
 558:                     $this->uses = array_flip($this->uses);
 559:                     unset($this->uses[$pluginDot . $this->modelClass]);
 560:                     $this->uses = array_flip($this->uses);
 561:                     array_unshift($this->uses, $pluginDot . $this->modelClass);
 562:                 }
 563:             } elseif (
 564:                 ($this->uses !== null || $this->uses !== false) &&
 565:                 is_array($this->uses) && !empty($appVars['uses'])
 566:             ) {
 567:                 $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
 568:             }
 569:             $this->_mergeVars($merge, $this->_mergeParent, true);
 570:         }
 571:     }
 572: 
 573: /**
 574:  * Loads Model classes based on the uses property
 575:  * see Controller::loadModel(); for more info.
 576:  * Loads Components and prepares them for initialization.
 577:  *
 578:  * @return mixed true if models found and instance created.
 579:  * @see Controller::loadModel()
 580:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
 581:  * @throws MissingModelException
 582:  */
 583:     public function constructClasses() {
 584:         $this->_mergeControllerVars();
 585:         $this->Components->init($this);
 586:         if ($this->uses) {
 587:             $this->uses = (array) $this->uses;
 588:             list(, $this->modelClass) = pluginSplit(current($this->uses));
 589:         }
 590:         return true;
 591:     }
 592: 
 593: /**
 594:  * Perform the startup process for this controller.
 595:  * Fire the Components and Controller callbacks in the correct order.
 596:  *
 597:  * - Initializes components, which fires their `initialize` callback
 598:  * - Calls the controller `beforeFilter`.
 599:  * - triggers Component `startup` methods.
 600:  *
 601:  * @return void
 602:  */
 603:     public function startupProcess() {
 604:         $this->Components->trigger('initialize', array(&$this));
 605:         $this->beforeFilter();
 606:         $this->Components->trigger('startup', array(&$this));
 607:     }
 608: 
 609: /**
 610:  * Perform the various shutdown processes for this controller.
 611:  * Fire the Components and Controller callbacks in the correct order.
 612:  *
 613:  * - triggers the component `shutdown` callback.
 614:  * - calls the Controller's `afterFilter` method.
 615:  *
 616:  * @return void
 617:  */
 618:     public function shutdownProcess() {
 619:         $this->Components->trigger('shutdown', array(&$this));
 620:         $this->afterFilter();
 621:     }
 622: 
 623: /**
 624:  * Queries & sets valid HTTP response codes & messages.
 625:  *
 626:  * @param mixed $code If $code is an integer, then the corresponding code/message is
 627:  *        returned if it exists, null if it does not exist. If $code is an array,
 628:  *        then the 'code' and 'message' keys of each nested array are added to the default
 629:  *        HTTP codes. Example:
 630:  *
 631:  *        httpCodes(404); // returns array(404 => 'Not Found')
 632:  *
 633:  *        httpCodes(array(
 634:  *            701 => 'Unicorn Moved',
 635:  *            800 => 'Unexpected Minotaur'
 636:  *        )); // sets these new values, and returns true
 637:  *
 638:  * @return mixed Associative array of the HTTP codes as keys, and the message
 639:  *    strings as values, or null of the given $code does not exist.
 640:  * @deprecated Use CakeResponse::httpCodes();
 641:  */
 642:     public function httpCodes($code = null) {
 643:         return $this->response->httpCodes($code);
 644:     }
 645: 
 646: /**
 647:  * Loads and instantiates models required by this controller.
 648:  * If the model is non existent, it will throw a missing database table error, as Cake generates
 649:  * dynamic models for the time being.
 650:  *
 651:  * @param string $modelClass Name of model class to load
 652:  * @param mixed $id Initial ID the instanced model class should have
 653:  * @return mixed true when single model found and instance created, error returned if model not found.
 654:  * @throws MissingModelException if the model class cannot be found.
 655:  */
 656:     public function loadModel($modelClass = null, $id = null) {
 657:         if ($modelClass === null) {
 658:             $modelClass = $this->modelClass;
 659:         }
 660: 
 661:         $this->uses = ($this->uses) ? $this->uses : array();
 662:         if (!in_array($modelClass, $this->uses)) {
 663:             $this->uses[] = $modelClass;
 664:         }
 665: 
 666:         list($plugin, $modelClass) = pluginSplit($modelClass, true);
 667: 
 668:         $this->{$modelClass} = ClassRegistry::init(array(
 669:             'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
 670:         ));
 671:         if (!$this->{$modelClass}) {
 672:             throw new MissingModelException($modelClass);
 673:         }
 674:         return true;
 675:     }
 676: 
 677: /**
 678:  * Redirects to given $url, after turning off $this->autoRender.
 679:  * Script execution is halted after the redirect.
 680:  *
 681:  * @param mixed $url A string or array-based URL pointing to another location within the app,
 682:  *     or an absolute URL
 683:  * @param integer $status Optional HTTP status code (eg: 404)
 684:  * @param boolean $exit If true, exit() will be called after the redirect
 685:  * @return mixed void if $exit = false. Terminates script if $exit = true
 686:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
 687:  */
 688:     public function redirect($url, $status = null, $exit = true) {
 689:         $this->autoRender = false;
 690: 
 691:         if (is_array($status)) {
 692:             extract($status, EXTR_OVERWRITE);
 693:         }
 694:         $response = $this->Components->trigger(
 695:             'beforeRedirect',
 696:             array(&$this, $url, $status, $exit),
 697:             array('break' => true, 'breakOn' => false, 'collectReturn' => true)
 698:         );
 699: 
 700:         if ($response === false) {
 701:             return;
 702:         }
 703:         extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
 704: 
 705:         $response = $this->beforeRedirect($url, $status, $exit);
 706:         if ($response === false) {
 707:             return;
 708:         }
 709:         extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
 710: 
 711:         if (function_exists('session_write_close')) {
 712:             session_write_close();
 713:         }
 714: 
 715:         if (!empty($status) && is_string($status)) {
 716:             $codes = array_flip($this->response->httpCodes());
 717:             if (isset($codes[$status])) {
 718:                 $status = $codes[$status];
 719:             }
 720:         }
 721: 
 722:         if ($url !== null) {
 723:             $this->response->header('Location', Router::url($url, true));
 724:         }
 725: 
 726:         if (!empty($status) && ($status >= 300 && $status < 400)) {
 727:             $this->response->statusCode($status);
 728:         }
 729: 
 730:         if ($exit) {
 731:             $this->response->send();
 732:             $this->_stop();
 733:         }
 734:     }
 735: 
 736: /**
 737:  * Parse beforeRedirect Response
 738:  *
 739:  * @param mixed $response Response from beforeRedirect callback
 740:  * @param mixed $url The same value of beforeRedirect
 741:  * @param integer $status The same value of beforeRedirect
 742:  * @param boolean $exit The same value of beforeRedirect
 743:  * @return array Array with keys url, status and exit
 744:  */
 745:     protected function _parseBeforeRedirect($response, $url, $status, $exit) {
 746:         if (is_array($response)) {
 747:             foreach ($response as $resp) {
 748:                 if (is_array($resp) && isset($resp['url'])) {
 749:                     extract($resp, EXTR_OVERWRITE);
 750:                 } elseif ($resp !== null) {
 751:                     $url = $resp;
 752:                 }
 753:             }
 754:         }
 755:         return compact('url', 'status', 'exit');
 756:     }
 757: 
 758: /**
 759:  * Convenience and object wrapper method for CakeResponse::header().
 760:  *
 761:  * @param string $status The header message that is being set.
 762:  * @return void
 763:  * @deprecated Use CakeResponse::header()
 764:  */
 765:     public function header($status) {
 766:         $this->response->header($status);
 767:     }
 768: 
 769: /**
 770:  * Saves a variable for use inside a view template.
 771:  *
 772:  * @param mixed $one A string or an array of data.
 773:  * @param mixed $two Value in case $one is a string (which then works as the key).
 774:  *   Unused if $one is an associative array, otherwise serves as the values to $one's keys.
 775:  * @return void
 776:  * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
 777:  */
 778:     public function set($one, $two = null) {
 779:         if (is_array($one)) {
 780:             if (is_array($two)) {
 781:                 $data = array_combine($one, $two);
 782:             } else {
 783:                 $data = $one;
 784:             }
 785:         } else {
 786:             $data = array($one => $two);
 787:         }
 788:         $this->viewVars = $data + $this->viewVars;
 789:     }
 790: 
 791: /**
 792:  * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
 793:  *
 794:  * Examples:
 795:  *
 796:  * {{{
 797:  * setAction('another_action');
 798:  * setAction('action_with_parameters', $parameter1);
 799:  * }}}
 800:  *
 801:  * @param string $action The new action to be 'redirected' to
 802:  * @param mixed  Any other parameters passed to this method will be passed as
 803:  *    parameters to the new action.
 804:  * @return mixed Returns the return value of the called action
 805:  */
 806:     public function setAction($action) {
 807:         $this->request->params['action'] = $action;
 808:         $this->view = $action;
 809:         $args = func_get_args();
 810:         unset($args[0]);
 811:         return call_user_func_array(array(&$this, $action), $args);
 812:     }
 813: 
 814: /**
 815:  * Returns number of errors in a submitted FORM.
 816:  *
 817:  * @return integer Number of errors
 818:  */
 819:     public function validate() {
 820:         $args = func_get_args();
 821:         $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
 822: 
 823:         if ($errors === false) {
 824:             return 0;
 825:         }
 826:         return count($errors);
 827:     }
 828: 
 829: /**
 830:  * Validates models passed by parameters. Example:
 831:  *
 832:  * `$errors = $this->validateErrors($this->Article, $this->User);`
 833:  *
 834:  * @param mixed A list of models as a variable argument
 835:  * @return array Validation errors, or false if none
 836:  */
 837:     public function validateErrors() {
 838:         $objects = func_get_args();
 839: 
 840:         if (empty($objects)) {
 841:             return false;
 842:         }
 843: 
 844:         $errors = array();
 845:         foreach ($objects as $object) {
 846:             if (isset($this->{$object->alias})) {
 847:                 $object = $this->{$object->alias};
 848:             }
 849:             $object->set($object->data);
 850:             $errors = array_merge($errors, $object->invalidFields());
 851:         }
 852: 
 853:         return $this->validationErrors = (!empty($errors) ? $errors : false);
 854:     }
 855: 
 856: /**
 857:  * Instantiates the correct view class, hands it its data, and uses it to render the view output.
 858:  *
 859:  * @param string $view View to use for rendering
 860:  * @param string $layout Layout to use
 861:  * @return CakeResponse A response object containing the rendered view.
 862:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
 863:  */
 864:     public function render($view = null, $layout = null) {
 865:         $this->beforeRender();
 866:         $this->Components->trigger('beforeRender', array(&$this));
 867: 
 868:         $viewClass = $this->viewClass;
 869:         if ($this->viewClass != 'View') {
 870:             list($plugin, $viewClass) = pluginSplit($viewClass, true);
 871:             $viewClass = $viewClass . 'View';
 872:             App::uses($viewClass, $plugin . 'View');
 873:         }
 874: 
 875:         $View = new $viewClass($this);
 876: 
 877:         if (!empty($this->uses)) {
 878:             foreach ($this->uses as $model) {
 879:                 list($plugin, $className) = pluginSplit($model);
 880:                 $this->request->params['models'][$className] = compact('plugin', 'className');
 881:             }
 882:         }
 883:         if (!empty($this->modelClass) && ($this->uses === false || $this->uses === array())) {
 884:             $this->request->params['models'][$this->modelClass] = array('plugin' => $this->plugin, 'className' => $this->modelClass);
 885:         }
 886: 
 887:         $models = ClassRegistry::keys();
 888:         foreach ($models as $currentModel) {
 889:             $currentObject = ClassRegistry::getObject($currentModel);
 890:             if (is_a($currentObject, 'Model')) {
 891:                 $className = get_class($currentObject);
 892:                 list($plugin) = pluginSplit(App::location($className));
 893:                 $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
 894:                 $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
 895:             }
 896:         }
 897: 
 898:         $this->autoRender = false;
 899:         $this->View = $View;
 900:         $this->response->body($View->render($view, $layout));
 901:         return $this->response;
 902:     }
 903: 
 904: /**
 905:  * Returns the referring URL for this request.
 906:  *
 907:  * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
 908:  * @param boolean $local If true, restrict referring URLs to local server
 909:  * @return string Referring URL
 910:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
 911:  */
 912:     public function referer($default = null, $local = false) {
 913:         if ($this->request) {
 914:             $referer = $this->request->referer($local);
 915:             if ($referer == '/' && $default != null) {
 916:                 return Router::url($default, true);
 917:             }
 918:             return $referer;
 919:         }
 920:         return '/';
 921:     }
 922: 
 923: /**
 924:  * Forces the user's browser not to cache the results of the current request.
 925:  *
 926:  * @return void
 927:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
 928:  * @deprecated Use CakeResponse::disableCache()
 929:  */
 930:     public function disableCache() {
 931:         $this->response->disableCache();
 932:     }
 933: 
 934: /**
 935:  * Shows a message to the user for $pause seconds, then redirects to $url.
 936:  * Uses flash.ctp as the default layout for the message.
 937:  * Does not work if the current debug level is higher than 0.
 938:  *
 939:  * @param string $message Message to display to the user
 940:  * @param mixed $url Relative string or array-based URL to redirect to after the time expires
 941:  * @param integer $pause Time to show the message
 942:  * @param string $layout Layout you want to use, defaults to 'flash'
 943:  * @return void Renders flash layout
 944:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
 945:  */
 946:     public function flash($message, $url, $pause = 1, $layout = 'flash') {
 947:         $this->autoRender = false;
 948:         $this->set('url', Router::url($url));
 949:         $this->set('message', $message);
 950:         $this->set('pause', $pause);
 951:         $this->set('page_title', $message);
 952:         $this->render(false, $layout);
 953:     }
 954: 
 955: /**
 956:  * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
 957:  *
 958:  * @param array $data POST'ed data organized by model and field
 959:  * @param mixed $op A string containing an SQL comparison operator, or an array matching operators
 960:  *        to fields
 961:  * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
 962:  * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
 963:  *        included in the returned conditions
 964:  * @return array An array of model conditions
 965:  * @deprecated
 966:  */
 967:     public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
 968:         if (!is_array($data) || empty($data)) {
 969:             if (!empty($this->request->data)) {
 970:                 $data = $this->request->data;
 971:             } else {
 972:                 return null;
 973:             }
 974:         }
 975:         $cond = array();
 976: 
 977:         if ($op === null) {
 978:             $op = '';
 979:         }
 980: 
 981:         $arrayOp = is_array($op);
 982:         foreach ($data as $model => $fields) {
 983:             foreach ($fields as $field => $value) {
 984:                 $key = $model . '.' . $field;
 985:                 $fieldOp = $op;
 986:                 if ($arrayOp) {
 987:                     if (array_key_exists($key, $op)) {
 988:                         $fieldOp = $op[$key];
 989:                     } elseif (array_key_exists($field, $op)) {
 990:                         $fieldOp = $op[$field];
 991:                     } else {
 992:                         $fieldOp = false;
 993:                     }
 994:                 }
 995:                 if ($exclusive && $fieldOp === false) {
 996:                     continue;
 997:                 }
 998:                 $fieldOp = strtoupper(trim($fieldOp));
 999:                 if ($fieldOp === 'LIKE') {
1000:                     $key = $key.' LIKE';
1001:                     $value = '%' . $value . '%';
1002:                 } elseif ($fieldOp && $fieldOp != '=') {
1003:                     $key = $key.' ' . $fieldOp;
1004:                 }
1005:                 $cond[$key] = $value;
1006:             }
1007:         }
1008:         if ($bool != null && strtoupper($bool) != 'AND') {
1009:             $cond = array($bool => $cond);
1010:         }
1011:         return $cond;
1012:     }
1013: 
1014: /**
1015:  * Handles automatic pagination of model records.
1016:  *
1017:  * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
1018:  * @param mixed $scope Conditions to use while paginating
1019:  * @param array $whitelist List of allowed options for paging
1020:  * @return array Model query results
1021:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
1022:  * @deprecated Use PaginatorComponent instead
1023:  */
1024:     public function paginate($object = null, $scope = array(), $whitelist = array()) {
1025:         return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
1026:     }
1027: 
1028: /**
1029:  * Called before the controller action.  You can use this method to configure and customize components
1030:  * or perform logic that needs to happen before each controller action.
1031:  *
1032:  * @return void
1033:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1034:  */
1035:     public function beforeFilter() {
1036:     }
1037: 
1038: /**
1039:  * Called after the controller action is run, but before the view is rendered. You can use this method
1040:  * to perform logic or set view variables that are required on every request.
1041:  *
1042:  * @return void
1043:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1044:  */
1045:     public function beforeRender() {
1046:     }
1047: 
1048: /**
1049:  * The beforeRedirect method is invoked when the controller's redirect method is called but before any
1050:  * further action. If this method returns false the controller will not continue on to redirect the request.
1051:  * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
1052:  * return a string which will be interpreted as the url to redirect to or return associative array with
1053:  * key 'url' and optionally 'status' and 'exit'.
1054:  *
1055:  * @param mixed $url A string or array-based URL pointing to another location within the app,
1056:  *     or an absolute URL
1057:  * @param integer $status Optional HTTP status code (eg: 404)
1058:  * @param boolean $exit If true, exit() will be called after the redirect
1059:  * @return boolean
1060:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1061:  */
1062:     public function beforeRedirect($url, $status = null, $exit = true) {
1063:         return true;
1064:     }
1065: 
1066: /**
1067:  * Called after the controller action is run and rendered.
1068:  *
1069:  * @return void
1070:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1071:  */
1072:     public function afterFilter() {
1073:     }
1074: 
1075: /**
1076:  * This method should be overridden in child classes.
1077:  *
1078:  * @param string $method name of method called example index, edit, etc.
1079:  * @return boolean Success
1080:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1081:  */
1082:     public function beforeScaffold($method) {
1083:         return true;
1084:     }
1085: 
1086: /**
1087:  * Alias to beforeScaffold()
1088:  *
1089:  * @param string $method
1090:  * @return boolean
1091:  * @see Controller::beforeScaffold()
1092:  * @deprecated
1093:  */
1094:     protected function _beforeScaffold($method) {
1095:         return $this->beforeScaffold($method);
1096:     }
1097: 
1098: /**
1099:  * This method should be overridden in child classes.
1100:  *
1101:  * @param string $method name of method called either edit or update.
1102:  * @return boolean Success
1103:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1104:  */
1105:     public function afterScaffoldSave($method) {
1106:         return true;
1107:     }
1108: 
1109: /**
1110:  * Alias to afterScaffoldSave()
1111:  *
1112:  * @param string $method
1113:  * @return boolean
1114:  * @see Controller::afterScaffoldSave()
1115:  * @deprecated
1116:  */
1117:     protected function _afterScaffoldSave($method) {
1118:         return $this->afterScaffoldSave($method);
1119:     }
1120: 
1121: /**
1122:  * This method should be overridden in child classes.
1123:  *
1124:  * @param string $method name of method called either edit or update.
1125:  * @return boolean Success
1126:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1127:  */
1128:     public function afterScaffoldSaveError($method) {
1129:         return true;
1130:     }
1131: 
1132: /**
1133:  * Alias to afterScaffoldSaveError()
1134:  *
1135:  * @param string $method
1136:  * @return boolean
1137:  * @see Controller::afterScaffoldSaveError()
1138:  * @deprecated
1139:  */
1140:     protected function _afterScaffoldSaveError($method) {
1141:         return $this->afterScaffoldSaveError($method);
1142:     }
1143: 
1144: /**
1145:  * This method should be overridden in child classes.
1146:  * If not it will render a scaffold error.
1147:  * Method MUST return true in child classes
1148:  *
1149:  * @param string $method name of method called example index, edit, etc.
1150:  * @return boolean Success
1151:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1152:  */
1153:     public function scaffoldError($method) {
1154:         return false;
1155:     }
1156: 
1157: /**
1158:  * Alias to scaffoldError()
1159:  *
1160:  * @param string $method
1161:  * @return boolean
1162:  * @see Controller::scaffoldError()
1163:  * @deprecated
1164:  */
1165:     protected function _scaffoldError($method) {
1166:         return $this->scaffoldError($method);
1167:     }
1168: 
1169: }
1170: 
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