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

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

Packages

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

Classes

  • 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();
  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:             $merge = array('components', 'helpers');
 561:             $this->_mergeVars($merge, $this->_mergeParent, true);
 562:         }
 563: 
 564:         if ($this->uses === null) {
 565:             $this->uses = false;
 566:         }
 567:         if ($this->uses === true) {
 568:             $this->uses = array($pluginDot . $this->modelClass);
 569:         }
 570:         if (isset($appVars['uses']) && $appVars['uses'] === $this->uses) {
 571:             array_unshift($this->uses, $pluginDot . $this->modelClass);
 572:         }
 573:         if ($pluginController) {
 574:             $pluginVars = get_class_vars($pluginController);
 575:         }
 576:         if ($this->uses !== false) {
 577:             $this->_mergeUses($pluginVars);
 578:             $this->_mergeUses($appVars);
 579:         } else {
 580:             $this->uses = array();
 581:             $this->modelClass = '';
 582:         }
 583:     }
 584: 
 585: /**
 586:  * Helper method for merging the $uses property together.
 587:  *
 588:  * Merges the elements not already in $this->uses into
 589:  * $this->uses.
 590:  *
 591:  * @param array $merge The data to merge in.
 592:  * @return void
 593:  */
 594:     protected function _mergeUses($merge) {
 595:         if (!isset($merge['uses'])) {
 596:             return;
 597:         }
 598:         if ($merge['uses'] === true) {
 599:             return;
 600:         }
 601:         $this->uses = array_merge(
 602:             $this->uses,
 603:             array_diff($merge['uses'], $this->uses)
 604:         );
 605:     }
 606: 
 607: /**
 608:  * Returns a list of all events that will fire in the controller during it's lifecycle.
 609:  * You can override this function to add you own listener callbacks
 610:  *
 611:  * @return array
 612:  */
 613:     public function implementedEvents() {
 614:         return array(
 615:             'Controller.initialize' => 'beforeFilter',
 616:             'Controller.beforeRender' => 'beforeRender',
 617:             'Controller.beforeRedirect' => array('callable' => 'beforeRedirect', 'passParams' => true),
 618:             'Controller.shutdown' => 'afterFilter'
 619:         );
 620:     }
 621: 
 622: /**
 623:  * Loads Model classes based on the uses property
 624:  * see Controller::loadModel(); for more info.
 625:  * Loads Components and prepares them for initialization.
 626:  *
 627:  * @return mixed true if models found and instance created.
 628:  * @see Controller::loadModel()
 629:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
 630:  * @throws MissingModelException
 631:  */
 632:     public function constructClasses() {
 633:         $this->_mergeControllerVars();
 634:         $this->Components->init($this);
 635:         if ($this->uses) {
 636:             $this->uses = (array)$this->uses;
 637:             list(, $this->modelClass) = pluginSplit(current($this->uses));
 638:         }
 639:         return true;
 640:     }
 641: 
 642: /**
 643:  * Returns the CakeEventManager manager instance that is handling any callbacks.
 644:  * You can use this instance to register any new listeners or callbacks to the
 645:  * controller events, or create your own events and trigger them at will.
 646:  *
 647:  * @return CakeEventManager
 648:  */
 649:     public function getEventManager() {
 650:         if (empty($this->_eventManager)) {
 651:             $this->_eventManager = new CakeEventManager();
 652:             $this->_eventManager->attach($this->Components);
 653:             $this->_eventManager->attach($this);
 654:         }
 655:         return $this->_eventManager;
 656:     }
 657: 
 658: /**
 659:  * Perform the startup process for this controller.
 660:  * Fire the Components and Controller callbacks in the correct order.
 661:  *
 662:  * - Initializes components, which fires their `initialize` callback
 663:  * - Calls the controller `beforeFilter`.
 664:  * - triggers Component `startup` methods.
 665:  *
 666:  * @return void
 667:  */
 668:     public function startupProcess() {
 669:         $this->getEventManager()->dispatch(new CakeEvent('Controller.initialize', $this));
 670:         $this->getEventManager()->dispatch(new CakeEvent('Controller.startup', $this));
 671:     }
 672: 
 673: /**
 674:  * Perform the various shutdown processes for this controller.
 675:  * Fire the Components and Controller callbacks in the correct order.
 676:  *
 677:  * - triggers the component `shutdown` callback.
 678:  * - calls the Controller's `afterFilter` method.
 679:  *
 680:  * @return void
 681:  */
 682:     public function shutdownProcess() {
 683:         $this->getEventManager()->dispatch(new CakeEvent('Controller.shutdown', $this));
 684:     }
 685: 
 686: /**
 687:  * Queries & sets valid HTTP response codes & messages.
 688:  *
 689:  * @param integer|array $code If $code is an integer, then the corresponding code/message is
 690:  *        returned if it exists, null if it does not exist. If $code is an array,
 691:  *        then the 'code' and 'message' keys of each nested array are added to the default
 692:  *        HTTP codes. Example:
 693:  *
 694:  *        httpCodes(404); // returns array(404 => 'Not Found')
 695:  *
 696:  *        httpCodes(array(
 697:  *            701 => 'Unicorn Moved',
 698:  *            800 => 'Unexpected Minotaur'
 699:  *        )); // sets these new values, and returns true
 700:  *
 701:  * @return array Associative array of the HTTP codes as keys, and the message
 702:  *    strings as values, or null of the given $code does not exist.
 703:  * @deprecated Use CakeResponse::httpCodes();
 704:  */
 705:     public function httpCodes($code = null) {
 706:         return $this->response->httpCodes($code);
 707:     }
 708: 
 709: /**
 710:  * Loads and instantiates models required by this controller.
 711:  * If the model is non existent, it will throw a missing database table error, as Cake generates
 712:  * dynamic models for the time being.
 713:  *
 714:  * @param string $modelClass Name of model class to load
 715:  * @param integer|string $id Initial ID the instanced model class should have
 716:  * @return mixed true when single model found and instance created, error returned if model not found.
 717:  * @throws MissingModelException if the model class cannot be found.
 718:  */
 719:     public function loadModel($modelClass = null, $id = null) {
 720:         if ($modelClass === null) {
 721:             $modelClass = $this->modelClass;
 722:         }
 723: 
 724:         $this->uses = ($this->uses) ? (array)$this->uses : array();
 725:         if (!in_array($modelClass, $this->uses)) {
 726:             $this->uses[] = $modelClass;
 727:         }
 728: 
 729:         list($plugin, $modelClass) = pluginSplit($modelClass, true);
 730: 
 731:         $this->{$modelClass} = ClassRegistry::init(array(
 732:             'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
 733:         ));
 734:         if (!$this->{$modelClass}) {
 735:             throw new MissingModelException($modelClass);
 736:         }
 737:         return true;
 738:     }
 739: 
 740: /**
 741:  * Redirects to given $url, after turning off $this->autoRender.
 742:  * Script execution is halted after the redirect.
 743:  *
 744:  * @param string|array $url A string or array-based URL pointing to another location within the app,
 745:  *     or an absolute URL
 746:  * @param integer $status Optional HTTP status code (eg: 404)
 747:  * @param boolean $exit If true, exit() will be called after the redirect
 748:  * @return mixed void if $exit = false. Terminates script if $exit = true
 749:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
 750:  */
 751:     public function redirect($url, $status = null, $exit = true) {
 752:         $this->autoRender = false;
 753: 
 754:         if (is_array($status)) {
 755:             extract($status, EXTR_OVERWRITE);
 756:         }
 757:         $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit));
 758: 
 759:         list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true);
 760:         $this->getEventManager()->dispatch($event);
 761: 
 762:         if ($event->isStopped()) {
 763:             return;
 764:         }
 765:         $response = $event->result;
 766:         extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
 767: 
 768:         if ($url !== null) {
 769:             $this->response->header('Location', Router::url($url, true));
 770:         }
 771: 
 772:         if (is_string($status)) {
 773:             $codes = array_flip($this->response->httpCodes());
 774:             if (isset($codes[$status])) {
 775:                 $status = $codes[$status];
 776:             }
 777:         }
 778: 
 779:         if ($status) {
 780:             $this->response->statusCode($status);
 781:         }
 782: 
 783:         if ($exit) {
 784:             $this->response->send();
 785:             $this->_stop();
 786:         }
 787:     }
 788: 
 789: /**
 790:  * Parse beforeRedirect Response
 791:  *
 792:  * @param mixed $response Response from beforeRedirect callback
 793:  * @param string|array $url The same value of beforeRedirect
 794:  * @param integer $status The same value of beforeRedirect
 795:  * @param boolean $exit The same value of beforeRedirect
 796:  * @return array Array with keys url, status and exit
 797:  */
 798:     protected function _parseBeforeRedirect($response, $url, $status, $exit) {
 799:         if (is_array($response) && array_key_exists(0, $response)) {
 800:             foreach ($response as $resp) {
 801:                 if (is_array($resp) && isset($resp['url'])) {
 802:                     extract($resp, EXTR_OVERWRITE);
 803:                 } elseif ($resp !== null) {
 804:                     $url = $resp;
 805:                 }
 806:             }
 807:         } elseif (is_array($response)) {
 808:             extract($response, EXTR_OVERWRITE);
 809:         }
 810:         return compact('url', 'status', 'exit');
 811:     }
 812: 
 813: /**
 814:  * Convenience and object wrapper method for CakeResponse::header().
 815:  *
 816:  * @param string $status The header message that is being set.
 817:  * @return void
 818:  * @deprecated Use CakeResponse::header()
 819:  */
 820:     public function header($status) {
 821:         $this->response->header($status);
 822:     }
 823: 
 824: /**
 825:  * Saves a variable for use inside a view template.
 826:  *
 827:  * @param string|array $one A string or an array of data.
 828:  * @param string|array $two Value in case $one is a string (which then works as the key).
 829:  *   Unused if $one is an associative array, otherwise serves as the values to $one's keys.
 830:  * @return void
 831:  * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
 832:  */
 833:     public function set($one, $two = null) {
 834:         if (is_array($one)) {
 835:             if (is_array($two)) {
 836:                 $data = array_combine($one, $two);
 837:             } else {
 838:                 $data = $one;
 839:             }
 840:         } else {
 841:             $data = array($one => $two);
 842:         }
 843:         $this->viewVars = $data + $this->viewVars;
 844:     }
 845: 
 846: /**
 847:  * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
 848:  *
 849:  * Examples:
 850:  *
 851:  * {{{
 852:  * setAction('another_action');
 853:  * setAction('action_with_parameters', $parameter1);
 854:  * }}}
 855:  *
 856:  * @param string $action The new action to be 'redirected' to
 857:  * @param mixed  Any other parameters passed to this method will be passed as
 858:  *    parameters to the new action.
 859:  * @return mixed Returns the return value of the called action
 860:  */
 861:     public function setAction($action) {
 862:         $this->request->params['action'] = $action;
 863:         $this->view = $action;
 864:         $args = func_get_args();
 865:         unset($args[0]);
 866:         return call_user_func_array(array(&$this, $action), $args);
 867:     }
 868: 
 869: /**
 870:  * Returns number of errors in a submitted FORM.
 871:  *
 872:  * @return integer Number of errors
 873:  */
 874:     public function validate() {
 875:         $args = func_get_args();
 876:         $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
 877: 
 878:         if ($errors === false) {
 879:             return 0;
 880:         }
 881:         return count($errors);
 882:     }
 883: 
 884: /**
 885:  * Validates models passed by parameters. Example:
 886:  *
 887:  * `$errors = $this->validateErrors($this->Article, $this->User);`
 888:  *
 889:  * @param mixed A list of models as a variable argument
 890:  * @return array Validation errors, or false if none
 891:  */
 892:     public function validateErrors() {
 893:         $objects = func_get_args();
 894: 
 895:         if (empty($objects)) {
 896:             return false;
 897:         }
 898: 
 899:         $errors = array();
 900:         foreach ($objects as $object) {
 901:             if (isset($this->{$object->alias})) {
 902:                 $object = $this->{$object->alias};
 903:             }
 904:             $object->set($object->data);
 905:             $errors = array_merge($errors, $object->invalidFields());
 906:         }
 907: 
 908:         return $this->validationErrors = (!empty($errors) ? $errors : false);
 909:     }
 910: 
 911: /**
 912:  * Instantiates the correct view class, hands it its data, and uses it to render the view output.
 913:  *
 914:  * @param string $view View to use for rendering
 915:  * @param string $layout Layout to use
 916:  * @return CakeResponse A response object containing the rendered view.
 917:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
 918:  */
 919:     public function render($view = null, $layout = null) {
 920:         $event = new CakeEvent('Controller.beforeRender', $this);
 921:         $this->getEventManager()->dispatch($event);
 922:         if ($event->isStopped()) {
 923:             $this->autoRender = false;
 924:             return $this->response;
 925:         }
 926: 
 927:         if (!empty($this->uses) && is_array($this->uses)) {
 928:             foreach ($this->uses as $model) {
 929:                 list($plugin, $className) = pluginSplit($model);
 930:                 $this->request->params['models'][$className] = compact('plugin', 'className');
 931:             }
 932:         }
 933: 
 934:         $viewClass = $this->viewClass;
 935:         if ($this->viewClass != 'View') {
 936:             list($plugin, $viewClass) = pluginSplit($viewClass, true);
 937:             $viewClass = $viewClass . 'View';
 938:             App::uses($viewClass, $plugin . 'View');
 939:         }
 940: 
 941:         $View = new $viewClass($this);
 942: 
 943:         $models = ClassRegistry::keys();
 944:         foreach ($models as $currentModel) {
 945:             $currentObject = ClassRegistry::getObject($currentModel);
 946:             if (is_a($currentObject, 'Model')) {
 947:                 $className = get_class($currentObject);
 948:                 list($plugin) = pluginSplit(App::location($className));
 949:                 $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
 950:                 $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
 951:             }
 952:         }
 953: 
 954:         $this->autoRender = false;
 955:         $this->View = $View;
 956:         $this->response->body($View->render($view, $layout));
 957:         return $this->response;
 958:     }
 959: 
 960: /**
 961:  * Returns the referring URL for this request.
 962:  *
 963:  * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
 964:  * @param boolean $local If true, restrict referring URLs to local server
 965:  * @return string Referring URL
 966:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
 967:  */
 968:     public function referer($default = null, $local = false) {
 969:         if ($this->request) {
 970:             $referer = $this->request->referer($local);
 971:             if ($referer == '/' && $default != null) {
 972:                 return Router::url($default, true);
 973:             }
 974:             return $referer;
 975:         }
 976:         return '/';
 977:     }
 978: 
 979: /**
 980:  * Forces the user's browser not to cache the results of the current request.
 981:  *
 982:  * @return void
 983:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
 984:  * @deprecated Use CakeResponse::disableCache()
 985:  */
 986:     public function disableCache() {
 987:         $this->response->disableCache();
 988:     }
 989: 
 990: /**
 991:  * Shows a message to the user for $pause seconds, then redirects to $url.
 992:  * Uses flash.ctp as the default layout for the message.
 993:  * Does not work if the current debug level is higher than 0.
 994:  *
 995:  * @param string $message Message to display to the user
 996:  * @param string|array $url Relative string or array-based URL to redirect to after the time expires
 997:  * @param integer $pause Time to show the message
 998:  * @param string $layout Layout you want to use, defaults to 'flash'
 999:  * @return void Renders flash layout
1000:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
1001:  */
1002:     public function flash($message, $url, $pause = 1, $layout = 'flash') {
1003:         $this->autoRender = false;
1004:         $this->set('url', Router::url($url));
1005:         $this->set('message', $message);
1006:         $this->set('pause', $pause);
1007:         $this->set('page_title', $message);
1008:         $this->render(false, $layout);
1009:     }
1010: 
1011: /**
1012:  * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
1013:  *
1014:  * @param array $data POST'ed data organized by model and field
1015:  * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
1016:  *        to fields
1017:  * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
1018:  * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
1019:  *        included in the returned conditions
1020:  * @return array An array of model conditions
1021:  * @deprecated
1022:  */
1023:     public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
1024:         if (!is_array($data) || empty($data)) {
1025:             if (!empty($this->request->data)) {
1026:                 $data = $this->request->data;
1027:             } else {
1028:                 return null;
1029:             }
1030:         }
1031:         $cond = array();
1032: 
1033:         if ($op === null) {
1034:             $op = '';
1035:         }
1036: 
1037:         $arrayOp = is_array($op);
1038:         foreach ($data as $model => $fields) {
1039:             foreach ($fields as $field => $value) {
1040:                 $key = $model . '.' . $field;
1041:                 $fieldOp = $op;
1042:                 if ($arrayOp) {
1043:                     if (array_key_exists($key, $op)) {
1044:                         $fieldOp = $op[$key];
1045:                     } elseif (array_key_exists($field, $op)) {
1046:                         $fieldOp = $op[$field];
1047:                     } else {
1048:                         $fieldOp = false;
1049:                     }
1050:                 }
1051:                 if ($exclusive && $fieldOp === false) {
1052:                     continue;
1053:                 }
1054:                 $fieldOp = strtoupper(trim($fieldOp));
1055:                 if ($fieldOp === 'LIKE') {
1056:                     $key = $key . ' LIKE';
1057:                     $value = '%' . $value . '%';
1058:                 } elseif ($fieldOp && $fieldOp != '=') {
1059:                     $key = $key . ' ' . $fieldOp;
1060:                 }
1061:                 $cond[$key] = $value;
1062:             }
1063:         }
1064:         if ($bool != null && strtoupper($bool) != 'AND') {
1065:             $cond = array($bool => $cond);
1066:         }
1067:         return $cond;
1068:     }
1069: 
1070: /**
1071:  * Handles automatic pagination of model records.
1072:  *
1073:  * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
1074:  * @param string|array $scope Conditions to use while paginating
1075:  * @param array $whitelist List of allowed options for paging
1076:  * @return array Model query results
1077:  * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
1078:  * @deprecated Use PaginatorComponent instead
1079:  */
1080:     public function paginate($object = null, $scope = array(), $whitelist = array()) {
1081:         return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
1082:     }
1083: 
1084: /**
1085:  * Called before the controller action.  You can use this method to configure and customize components
1086:  * or perform logic that needs to happen before each controller action.
1087:  *
1088:  * @return void
1089:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1090:  */
1091:     public function beforeFilter() {
1092:     }
1093: 
1094: /**
1095:  * Called after the controller action is run, but before the view is rendered. You can use this method
1096:  * to perform logic or set view variables that are required on every request.
1097:  *
1098:  * @return void
1099:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1100:  */
1101:     public function beforeRender() {
1102:     }
1103: 
1104: /**
1105:  * The beforeRedirect method is invoked when the controller's redirect method is called but before any
1106:  * further action. If this method returns false the controller will not continue on to redirect the request.
1107:  * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
1108:  * return a string which will be interpreted as the url to redirect to or return associative array with
1109:  * key 'url' and optionally 'status' and 'exit'.
1110:  *
1111:  * @param string|array $url A string or array-based URL pointing to another location within the app,
1112:  *     or an absolute URL
1113:  * @param integer $status Optional HTTP status code (eg: 404)
1114:  * @param boolean $exit If true, exit() will be called after the redirect
1115:  * @return mixed
1116:  *   false to stop redirection event,
1117:  *   string controllers a new redirection url or
1118:  *   array with the keys url, status and exit to be used by the redirect method.
1119:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1120:  */
1121:     public function beforeRedirect($url, $status = null, $exit = true) {
1122:     }
1123: 
1124: /**
1125:  * Called after the controller action is run and rendered.
1126:  *
1127:  * @return void
1128:  * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
1129:  */
1130:     public function afterFilter() {
1131:     }
1132: 
1133: /**
1134:  * This method should be overridden in child classes.
1135:  *
1136:  * @param string $method name of method called example index, edit, etc.
1137:  * @return boolean Success
1138:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1139:  */
1140:     public function beforeScaffold($method) {
1141:         return true;
1142:     }
1143: 
1144: /**
1145:  * Alias to beforeScaffold()
1146:  *
1147:  * @param string $method
1148:  * @return boolean
1149:  * @see Controller::beforeScaffold()
1150:  * @deprecated
1151:  */
1152:     protected function _beforeScaffold($method) {
1153:         return $this->beforeScaffold($method);
1154:     }
1155: 
1156: /**
1157:  * This method should be overridden in child classes.
1158:  *
1159:  * @param string $method name of method called either edit or update.
1160:  * @return boolean Success
1161:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1162:  */
1163:     public function afterScaffoldSave($method) {
1164:         return true;
1165:     }
1166: 
1167: /**
1168:  * Alias to afterScaffoldSave()
1169:  *
1170:  * @param string $method
1171:  * @return boolean
1172:  * @see Controller::afterScaffoldSave()
1173:  * @deprecated
1174:  */
1175:     protected function _afterScaffoldSave($method) {
1176:         return $this->afterScaffoldSave($method);
1177:     }
1178: 
1179: /**
1180:  * This method should be overridden in child classes.
1181:  *
1182:  * @param string $method name of method called either edit or update.
1183:  * @return boolean Success
1184:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1185:  */
1186:     public function afterScaffoldSaveError($method) {
1187:         return true;
1188:     }
1189: 
1190: /**
1191:  * Alias to afterScaffoldSaveError()
1192:  *
1193:  * @param string $method
1194:  * @return boolean
1195:  * @see Controller::afterScaffoldSaveError()
1196:  * @deprecated
1197:  */
1198:     protected function _afterScaffoldSaveError($method) {
1199:         return $this->afterScaffoldSaveError($method);
1200:     }
1201: 
1202: /**
1203:  * This method should be overridden in child classes.
1204:  * If not it will render a scaffold error.
1205:  * Method MUST return true in child classes
1206:  *
1207:  * @param string $method name of method called example index, edit, etc.
1208:  * @return boolean Success
1209:  * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
1210:  */
1211:     public function scaffoldError($method) {
1212:         return false;
1213:     }
1214: 
1215: /**
1216:  * Alias to scaffoldError()
1217:  *
1218:  * @param string $method
1219:  * @return boolean
1220:  * @see Controller::scaffoldError()
1221:  * @deprecated
1222:  */
1223:     protected function _scaffoldError($method) {
1224:         return $this->scaffoldError($method);
1225:     }
1226: 
1227: }
1228: 
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