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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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