• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/165

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

165 Cards in this Set

  • Front
  • Back
Available class types
Controller, Model, and View classes, but also additional classes and objects that make development in MVC a little quicker and more enjoyable: Components, Behaviors, and Helpers
Controller Extensions ("Components") (class type)
A component aids in controller logic. Allows for logic to be shared between controllers. Eg. EmailComponent aids in sending emails; other controllers (or applications) can then use this email class to send email easily.
Callbacks (for controllers)
Allows developer to insert logic between CakePHPs core operations:

* beforeFilter(), executed before any controller action logic
* beforeRender(), executed after controller logic, but before the view is rendered
* afterFilter(), executed after all controller logic, including the view render. There may be no difference between afterRender() and afterFilter() unless you’ve manually made a call to render() in your controller action and have included some logic after that call.
View Extensions ("Helpers") (class type)
A helper aids in view logic as a component helps in controller logic. AjaxHelper for example aids in Ajax requests.
View class & Layouts/Elements
Every view rendered by a View class is placed inside a layout. Elements in this context are repeated snippets of View code.

These snippits receive a cpt extension although they are php/html code.
Model Extensions ("Behaviors") (class type)
Behaviors add functionality to your model by specifying your data structure. Eg. Identifying your model with the tree structure behavior will allow you to remove/add/shift nodes accordingly.
Other Model Extension Type: DataSource
Whereas the model generally represents you database values, other DataSources can be used to represent the data in other forms: RSS feeds, CSV files, LDAP entries, or iCal events. This can allow for association of data from different data sources.
Callbacks (for behaviors)
Callbacks for behaviors, work similarly to callbacks for controllers, allowing you to insert logic between core operations. Callbacks include:

* beforeFind()
* afterFind()
* beforeValidate()
* beforeSave()
* afterSave()
* beforeDelete()
* afterDelete()
Parent classes for Controllers, Helpers, and Behaviors
By adjusting the AppController (located at /app/app_controller.php), AppHelper (located at /app/app_helper.php) and AppModel (located at /app/app_model.php) files, you can make applications wide adjustments to these core application classes.
Route Definitions (for URL interpretation)
Route definitions tell your application how to map URLS. The default is: “/controller/action/var1/var2” maps to Controller::action($var1, $var2). This can be customized.
Plugins
A feature that is run in many different applications may be packaged into a plugin.
MVC layout
http://book.cakephp.org/view/21/A-Typical-CakePHP-Request
Cake File Structure - app, cake, vendors
The app file will control your files. The cake folder holds cake files. The vendors file holds third party PHP libraries.
The app folder: config
Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.
The app folder: controllers
Holds your contollers
The app folder: locale
Stores string files for internationalization.
Bootstrapping
Many PHP applications funnel server requests into a single (or few) PHP source file that sets up the environment and configuration for the application, manages sessions and caching, and invokes the dispatcher for their MVC framework. They can do more, but their main job is to take care of the consistent needs of every page of a web application.
String files (for internationalization)
All strings in a text that can be translated or adjusted by region.
The app folder: models
Holds models, behaviors, and datasources
The app folder: plugins
Holds plugin packages
The app folder: tmp
This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information.
The app folder: vendors
Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the App::import('vendor', 'name') function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure. We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups.
The app folder: views
Presentational files are placed here: elements, error pages, helpers, layouts, and view files.
The app folder: webroot
In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.
Table name, 'modified', and 'created' functionality
Naming our table 'posts' automatically hooks it to our Post model, and having fields called 'modified' and 'created' will be automagically managed by Cake.
Security hash - Form eg.
If we leave our form unsecured, it is very easy to remove the field from the data array (by using some basic hacking tool) and since it won’t be present in the array, the validation will be skipped and the form data will be saved with a blank name.

The Security component will create a hash based on the form fields produced by our Form Helper. If someone tampers with the form fields (by adding or removing or changing any field), the hash is not going to match with the expected one and the add() action will fail.
.htaccess
?Allows the URL to be rewritten.
httpd.conf
?An Apache configuration file that allows .htaccess overide.
Blog Tutorial
To set up a Model class for the posts table:
class Post extends AppModel {
var $name = 'Post';
}

Naming convention is very important in CakePHP. By naming our model Post, CakePHP can automatically infer that this model will be used in the PostsController, and will be tied to a database table called posts.
Blog Tutorial
To set up a Controller class for the posts:
Here is where the business logic for post interaction will happen. In a nutshell, it's the place where you play with the models and get post-related work done.

This new controller will be in a file called posts_controller.php inside the /app/controllers directory.

class PostsController extends AppController {

var $name = 'Posts';
}
Blog Tutorial
Build a controller for posts from the Post Model
class PostsController extends AppController {

var $name = 'Posts';

function index() {
$this->set('posts', $this->Post->find('all'));
}
}

The single instruction in the action uses set() to pass data from the controller to the view (which we'll create next). The line sets the view variable called 'posts' equal to the return value of the find('all') method of the Post model. Our Post model is automatically available at $this->Post because we've followed Cake's naming conventions.
Cake views: part or whole?
Cake views are just presentation-flavored fragments that fit inside an application's layout. For most applications they're HTML mixed with PHP, but they may end up as XML, CSV, or even binary data.
Blog Tutorial
Saving the View class
The view class will be placed in a folder titled after the controller in the view directory. It takes the ctp extension.

/views/posts/posts.ctp
Blog Tutorial
HtmlHelper class
The HtmlHelper class is used to make a link with a title and the location for the post.

<?php echo $html->link($post['Post']['title'],
"/posts/view/".$post['Post']['id']); ?>

CakePHP comes with a set of view helpers that make things like linking, form output, JavaScript and Ajax a snap.
URLs in Cake
When specifying URLs in Cake, you simply give a path relative to the base of the application, and Cake fills in the rest. As such, your URLs will typically take the form of /controller/action/param1/param2.
URLs in Cake
When specifying URLs in Cake, you simply give a path relative to the base of the application, and Cake fills in the rest. As such, your URLs will typically take the form of /controller/action/param1/param2.
Blog Tutorial
Ask controller to add $data tot he Post model and posts database
function add() {
if (!empty($this->data)) {
//check if data was submitted
if ($this->Post->save($this->data))
//try adding the data to the Post class using the save() method and the $this->data to reference the form inputs which were automatically logged using the input() method on of the FormHelper class
{
$this->flash('Your post has been saved.', '/posts');
//if the add() method is completed successfully, flash a successful message, and then redirect to /posts (/app/posts/index)
}
}
}
Forms interpreted by the controller...
When a user uses a form to POST data to your application, that information is available in $this->data. You can use the pr() to print it out if you want to see what it looks like.
$this->flash()
The $this->flash() function called is a controller method that flashes a message to the user for a second (using the flash layout) then forwards the user on to another URL (/posts, in this case).
save() (and validation)
Calling the save() method will check for validation errors and abort the save if any occur.
Form input through FormHelper
To take advantage of the validation features, you'll need to use Cake's FormHelper in your views. The FormHelper is available by default to all views at $form.
Creating a form with FormHelper
<!-- File: /app/views/posts/add.ctp -->

<h1>Add Post</h1>
<?php
echo $form->create('Post');
echo $form->input('title');
echo $form->input('body', array('rows' => '3'));
echo $form->end('Save Post');
?>

The FormHelper is available by default to all views at $form.
$form->create()
eg.

echo $form->create('Post');


<form>

If create() is called with no parameters supplied, it assumes you are building a form that submits to the current controller's add() action, via POST.

(Should it be named after the model, or does Post just mean it is being submitted by POST... I imagine it is named after the model, singular...)
$form->input()
eg.

echo $form->input('body', array('rows' => '3'));


The $form->input() method is used to create form elements of the same name. The first parameter tells CakePHP which field they correspond to, and the second parameter allows you to specify a wide array of options — in this case, the number of rows for the textarea.
$form->end()
eg.

echo $form->end('Save Post');

The $form->end() call generates a submit button and ends the form. If a string is supplied as the first parameter to end(), the FormHelper outputs a submit button named accordingly along with the closing form tag.
Where to validate
Validation rules are defined in the model.
Add Post link for Posts controller
to link to /app/views/posts/index.ctp :

<?php echo $html->link('Add Post','/posts/add')?>
$validate
Because input() has been used in view.ctp, $validate can be used in the model class.

var $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
Blog Tutorial
Delete post link (pay attention to all four arguments)
<?php echo $html->link('Delete', "/posts/delete/{$post['Post']['id']}", null, 'Are you sure?' )?>

This logic deletes the post specified by $id, and uses flash() to show the user a confirmation message before redirecting them on to /posts.

This view code also uses the HtmlHelper to prompt the user with a JavaScript confirmation dialog before they attempt to delete a post.
Controller, view work flow
Make the action, then the view.
Blog Tutorial
Edit posts controller logic
function edit($id = null) {
//default of $id = null (only if $id is not present)
$this->Post->id = $id;
if (empty($this->data)) {
$this->data = $this->Post->read();
//read() this post (show the post)
} else {
if ($this->Post->save($this->data))
//if not empty, save() this data (this method includes data validation)
{
$this->flash('Your post has been updated.','/posts');
//flash if this can be performed
}
}
}

This action first checks for submitted form data. If nothing was submitted, it finds the Post and hands it to the view. If some data has been submitted, try to save the data using Post model (or kick back and show the user the validation errors).
Blog Tutorial
Edit posts view element
echo $form->create('Post', array('action' => 'edit'));

CakePHP will assume that you are editing a model if the 'id' field is present in the data array. If no 'id' is present (look back at our add view), Cake will assume that you are inserting a new model when save() is called.
Default page in Routes file
By default, CakePHP responds to a request for the root of your site (i.e. http://www.example.com) using its PagesController, rendering a view called "home":

Router::connect ('/', array('controller'=>'pages', 'action'=>'display', 'home'));

This line connects the URL '/' with the default CakePHP home page. We want it to connect with our own controller, so add a line that looks like this (eg):

Router::connect ('/', array('controller'=>'posts', 'action'=>'index'));
/app/tmp directory - purpose and usability
CakePHP uses the /app/tmp directory for a number of different operations. Model descriptions, cached views, and session information are just a few examples.

As such, make sure the /app/tmp directory in your cake installation is writable by the web server user.
A production installation of CakePHP
(installation may require the rights to change the DocumentRoot on an Apache webservers)

Once unpacked on server, developers using Apache should set the DocumentRoot directive for the domain to:

DocumentRoot /cake_install/app/webroot

the DocumentRoot directive is found in the Apache httpd.conf file.
The /app, /cake and /app/webroot locations
In an advanced installation of cake, the /app, /cake and /app/webroot files can be located anywhere.
Specifying the /app, /cake and /app/webroot locations
To configure your Cake installation, you'll need to make some changes to /app/webroot/index.php. There are three constants that you'll need to edit: ROOT, APP_DIR, and CAKE_CORE_INCLUDE_PATH.

* ROOT should be set to the path of the directory that contains your app folder.
* APP_DIR should be set to the (base)name of your app folder.
* CAKE_CORE_INCLUDE_PATH should be set to the path of your CakePHP libraries folder.

eg. at http://book.cakephp.org/view/35/Advanced-Installation
Additional Class PAths
It’s occasionally useful to be able to share MVC classes between applications on the same system. If you want the same controller in both applications, you can use CakePHP’s bootstrap.php to bring these additional classes into view.

In bootstrap.php, define some specially-named variables to make CakePHP aware of other places to look for MVC classes...
Use Lighttpd when Apache's mod_rewrite doesn't work
While lighttpd features a rewrite module, it is not an equivalent of Apache's mod_rewrite. Full mod_rewrite functionalities are spread amongst Lighttpd's mod_rewrite, mod_magnet and mod_proxy.

CakePHP, however, mostly needs mod_magnet to redirect requests in order to work with pretty URLs.

To use pretty URLs with CakePHP and Lighttp, place this lua script in /etc/lighttpd/cake...

Then tell Lighttpd about your vhost...
CakePHP configuration
Either just setup your DB access info or...

You can easily add elements to the CakePHP core, configure custom URLs, and define custom inflections.
Option to incorporate a legacy
The $default connection array is used unless another connection is specified by the $useDbConfig property in a model. For example, if my application has an additional legacy database in addition to the default one, I could use it in my models by creating a new $legacy database connection array similar to the $default array, and by setting var $useDbConfig = ‘legacy’; in the appropriate models.
Elements of a db connection string with cake
driver: The name of the database driver this configuration array is for. Examples: mysql, postgres, sqlite, pear-drivername, adodb-drivername, mssql, oracle, or odbc.

persistent: Whether or not to use a persistent connection to the database.

host: The database server’s hostname (or IP address).

login: The username for the account.

password: The password for the account.

database: The name of the database for this connection to use.

prefix (optional): The string that prefixes every table name in the database. If your tables don’t have prefixes, set this to an empty string.

port (optional): The TCP port or Unix socket used to connect to the server.

encoding: Indicates what character set the to use to send SQL statements to the server. This defaults to the database's default encoding for all databases other than DB2. If you wish to use UTF-8 encoding with mysql/mysqli connections you must use 'utf8' without the hyphen.

schema Used in PostgreSQL database setups to specify which schema to use.
The Configuration Class
The main goal of Configure class is to keep centralized variables that can be shared between many objects. Remember to try to live by "convention over configuration" and you wont end up breaking the MVC structure we’ve set in place.

eg? <?php Configure::read('debug'); ?>
Configure methods
write, read, delete, load, version
Configuration write method
Used to store data in the application's configuration:

Configure::write('Company.name','Pizza, Inc.');
Configure::write('Company.slogan','Pizza for your body and soul');
Reading configuration information from within the application
Configure::read('Company.name'); //yields: 'Pizza, Inc.'
Configure::read('Company.slogan'); //yields: 'Pizza for your body and soul'

Configure::read('Company');

//yields:
array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
Deleting configuration information from within the application
Configure::delete('Company.name');
Loading configuration information from another file
Use this method to load configuration information from a specific file.

// /app/config/messages.php:
<?php
$config['Company']['name'] = 'Pizza, Inc.';
$config['Company']['slogan'] = 'Pizza for your body and soul';
$config['Company']['phone'] = '555-55-55';
?>

<?php
Configure::load('messages');
Configure::read('Company.name');
?>
version()
Returns the CakePHP version for the current application.
Core Configuration variables
debug, App.baseUrl, Routing.admin, Cache.disable, Cache.check, Session.save, Session.table, Session.database, Session.cookie, Session.timeout, Session.start, Session.checkAgent, Security.level, Security.salt. Acl.classname Acl.database
Core Configuration variables: debug
Changes CakePHP debugging output.

0 = Production mode. No output.
1 = Show errors and warnings.
2 = Show errors, warnings, and SQL.
3 = Show errors, warnings, SQL, and complete controller dump.
Core Configuration variables: App.baseUrl
Un-comment this definition if you don’t plan to use Apache’s mod_rewrite with CakePHP. Don’t forget to remove your .htaccess files too.
Core Configuration variables: Routing.admin
Un-comment this definition if you’d like to take advantage of CakePHP admin routes. Set this variable to the name of the admin route you’d like to use. More on this later.
Core Configuration variables: Cache.disable
When set to true, caching is disabled site-wide.
Core Configuration variables: Cache.check
If set to true, enables view caching. Enabling is still needed in the controllers, but this variable enables the detection of those settings.
Core Configuration variables:
Session.save
Tells CakePHP which session storage mechanism to use.

php = Use the default PHP session storage.
cake = Store session data in /app/tmp
database = store session data in a database table. Make sure to set up the table using the SQL file located at /app/config/sql/sessions.sql.
Core Configuration variables:
Session.table
The name of the table (not including any prefix) that stores session information.
Core Configuration variables:
Session.database
The name of the database that stores session information.
Core Configuration variables:
Session.cookie
The name of the cookie used to track sessions.
Core Configuration variables:
Session.timeout
Base session timeout in seconds. Actual value depends on Security.level.
Core Configuration variables:
Session.start
Automatically starts sessions when set to true.
Core Configuration variables:
Session.checkAgent
When set to false, CakePHP sessions will not check to ensure the user agent does not change between requests.
Core Configuration variables:
Security.level
The level of CakePHP security. The session timeout time defined in 'Session.timeout' is multiplied according to the settings here.

Valid values:
'high' = x 10
'medium' = x 100
'low' = x 300

'high' and 'medium' also enable session.referer_check

CakePHP session IDs are also regenerated between requests if 'Security.level' is set to 'high'.
Core Configuration variables:
Security.salt
A random string used in security hashing.
Core Configuration variables:
Acl.classname, Acl.database
Constants used for CakePHP’s Access Control List functionality. See the Access Control Lists chapter for more information.
Configuration Constant: LOG_ERROR
Error constant. Used for differentiating error logging and debugging. Currently PHP supports LOG_DEBUG.
Loading classes
All class and library loading should be done through App::import() now. App::import() ensures that a class is only loaded once, that the appropriate parent class has been loaded, and resolves paths automatically in most cases.
Using App::import()
App::import($type, $name, $parent, $search, $file, $return);

At first glance App::import seems complex, however in most use cases only 2 arguments are required.
Importing Core Libs
Core libraries such as Sanitize, and Xml can be loaded by:

App::import('Core', 'Sanitize');

The above would make the Sanitize class available for use.
Importing Controllers, Models, Components, Behaviors, and Helpers
All application related class should also be loaded with App::import()
Loading Controllers
App::import('Controller', 'MyController');

Calling App::import is equivalent to require'ing the file. It is important to realize that the class subsequently needs to be initialized.

<?php
// The same as require('controllers/users_controller.php');
App::import('Controller', 'Users');

// We need to load the class
$Users = new UsersController;

// If we want the model associations, components, etc to be loaded
$Users->constructClasses();
?>
Loading Models
App::import('Model', 'MyModel');
Loading Components
App::import('Component', 'Auth');
Loading Behaviors
App::import('Behavior', 'Tree');
Loading Helpers
App::import('Helper', 'Html');
Loading from Plugins
App::import('Model', 'PluginName.Comment');

Loading classes in plugins works much the same as loading app and core classes except you must specify the plugin you are loading from.
Loading Vendor Files - egs
App::import('Vendor', 'geshi');

App::import('Vendor', 'flickr/flickr');

App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));

App::import('Vendor', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));
Default Routing
URL pattern default routes:
http://example.com/controller/action/param1/param2/param3

The URL /posts/view maps to the view() action of the PostsController, and /products/viewClearance maps to the view_clearance() action of the ProductsController. If no action is specified in the URL, the index() method is assumed.
Accessing named parameters in URL
New in CakePHP 1.2 is the ability to use named parameters. You can name parameters and send their values using the URL. A request for /posts/view/title:first+post/category:general would result in a call to the view() action of the PostsController. In that action, you’d find the values of the title and category parameters inside $this->passedArgs[‘title’] and $this->passedArgs[‘category’] respectively.
Default routes examples
URL to controller action mapping using default routes:

URL: /monkeys/jump
Mapping: MonkeysController->jump();

URL: /products
Mapping: ProductsController->index();

URL: /tasks/view/45
Mapping: TasksController->view(45);

URL: /donations/view/recent/2001
Mapping: DonationsController->view('recent', '2001');

URL: /contents/view/chapter:models/section:associations
Mapping: ContentsController->view();
$this->passedArgs['chapter'] = 'models';
$this->passedArgs['section'] = 'associations';
Custom Route Configuraion
3.4.5.3 - 3.4.5.5

Defining Routes
Passing Parameters
Prefix Routing
Custom Inflections
There are occasions (especially for our non-English speaking friends) where you may run into situations where CakePHP's inflector (the class that pluralizes, singularizes, camelCases, and under_scores) might not work as you'd like. If CakePHP won't recognize your Foci or Fish, editing the custom inflections configuration file is where you can tell CakePHP about your special cases. This file is found in /app/config/inflections.php.

See: http://book.cakephp.org/view/47/Custom-Inflections
Bootstrapping
If you have any additional configuration needs, use CakePHP’s bootstrap file, found in /app/config/bootstrap.php. This file is executed just after CakePHP’s core bootstrapping.

This file is ideal for a number of common bootstrapping tasks:

* Defining convenience functions
* Registering global constants
* Defining additional model, view, and controller paths
Global Variables and Methods
In addition to defining new methods and variable in the bootstrapping file, you might also consider placing things in the AppController class. This class is a parent class to all of the controllers in your application. AppController is handy place to use controller callbacks and define methods to be used by all of your controllers.
Controller Actions
Actions are controller methods used to display views. An action is a single method of a controller. CakePHP’s dispatcher calls actions when an incoming request matches a URL to a controller’s action.
Controller $name attribute
Although the controller class takes a CamelCased name ending in Controller, its name attribute omits the 'Controller' part
Working with additional controllers in an action
Our RecipesController will have the Recipe model class available at $this->Recipe, and our ProductsController also features the Product model at $this->Product. However, when allowing a controller to access additional models through the $uses variable, the name of the current controller's model must also be included. This is illustrated in the example below.

<?php
class RecipesController extends AppController {
var $name = 'Recipes';

var $uses = array('Recipe', 'User');
var $helpers = array('Ajax');
var $components = array('Email');
}
?>
Default Helpers
The Html, Form, and Session Helpers are always available by default, as is the SessionComponent. To learn more about these classes, be sure to check out their respective sections later in this manual.

Each of these variables are merged with their inherited values, therefore it is not necessary (for example) to redeclare the Form helper, or anything that is declared in your App controller.
Declaring non default helpers
<?php
class RecipesController extends AppController {
var $name = 'Recipes';

var $uses = array('Recipe', 'User');
var $helpers = array('Ajax');
var $components = array('Email');
}
?>

Each of these variables are merged with their inherited values, therefore it is not necessary (for example) to redeclare the Form helper, or anything that is declared in your App controller.

Notice that the Model is redeclared
Setting a layout
<?php

// Using $layout to define an alternate layout

class RecipesController extends AppController {
function quickSave() {
$this->layout = 'ajax';
}
}

?>

The $layout attribute can be set to the name of a layout saved in /app/views/layouts. You specify a layout by setting $layout equal to the name of the layout file minus the .ctp extension.
Default layouts
If the $layout attribute has not been defined, CakePHP renders the default layout, default.ctp. If you haven’t defined one at /app/views/layouts/default.ctp, CakePHP’s core default layout will be rendered.
$pageTitle
<?php

// Using $pageTitle to define the page title

class RecipesController extends AppController {
function quickSave() {
$this->pageTitle = 'My search engine optimized title';
}
}

?>


You can also change the title of the page (that is located in the bar at the top of your browser) using $pageTitle. In order for this to work properly, your layout needs to include the $title_for_layout variable, at least between the <title> and </title> tags in the head of the HTML document.
pageTitle from within view
You can also set the page title from the view using $this->pageTitle (You must include the $this-> part.) This is recommended, as it better separates the logic from the layout and content. For a static page you must use $this->pageTitle in the view if you want a custom title.

If $this->pageTitle is not set, a title will be automatically generated based on the controller name, or the view file name in the case of a static page.
$params
Controller parameters are available at $this->params in your CakePHP controller. This variable is used to provide access to information about the current request. The most common usage of $this->params is to get access to information that has been handed to the controller via POST or GET operations.
$this->params['form']
$this->params['form']

Any POST data from any form is stored here, including information also found in $_FILES.
$this->params['admin']
$this->params['admin']

Is set to 1 if the current action was invoked via admin routing.
$this->params['bare']
$this->params['bare']

Stores 1 if the current layout is empty, 0 if not.
$this->params['ajax']
$this->params['ajax']

Stores 1 if the current request is an ajax call, 0 if not. This variable is only set if the RequestHandler Component is being used in the controller.
$this->params['controller']
$this->params['controller']

Stores the name of the current controller handling the request. For example, if the URL /posts/view/1 was requested, $this->params['controller'] would equal "posts".
$this->params['action']
$this->params['action']

Stores the name of the current action handling the request. For example, if the URL /posts/view/1 was requested, $this->params['action'] would equal "view".
$this->params['pass']
$this->params['pass']

Stores the GET query string passed with the current request. For example, if the URL /posts/view/?var1=3&var2=4 was requested, $this->params['pass'] would equal "?var1=3&var2=4".
$this->params['url']
$this->params['url']

Stores the current URL requested, along with key-value pairs of get variables. For example, if the URL /posts/view/?var1=3&var2=4 was called, $this->params['url'] would contain:

[url] => Array
(
[url] => posts/view
[var1] => 3
[var2] => 4
)
$this->data
$this->data

Used to handle POST data sent from the FormHelper forms to the controller.
how the FormHelper works
// The FormHelper is used to create a form element:
$form->text('User.first_name');

Which when rendered, looks something like:

*<*i*nput name="data[User][first_name]" value="" type="text" />




When the form is submitted to the controller via POST, the data shows up in this->data

//The submitted first name can be found here:
$this->data['User']['first_name'];
$this->params['prefix']
$this->params['prefix']

Set to the routing prefix. For example, this attribute would contain the string "admin" during a request to /admin/posts/someaction.
$this->params['named']
$this->params['named']

Stores any named parameters in the url query string in the form /key:value/. For example, if the URL /posts/view/var1:3/var2:4 was requested, $this->params['named'] would be an array containing:

[named] => Array
(
[var1] => 3
[var2] => 4
)
$cacheAction, $paginate
The $cacheAction attribute aids in caching views, and the $paginate attribute is used to set pagination defaults for the controller. For more information on how to use these attributes, check out their respective sections later on in this manual.
Controller Mehods - Link
For a complete list of controller methods and their descriptions visit the CakePHP API. Check out http://api.cakephp.org/1.2/class_controller.html.
set(string $var, mixed $value)
The set() method is the main way to send data from your controller to your view. Once you've used set(), the variable can be accessed in your view.
set method example
<?php

//First you pass data from the controller:

$this->set('color', 'pink');

//Then, in the view, you can utilize the data:
?>

You have selected <?php echo $color; ?> icing for the cake.
set and inflection
Array keys will be inflected before they are assigned to the view ('underscored_key' becomes 'underscoredKey', etc.):
render(string $action, string $layout, string $file)
The render() method is automatically called at the end of each requested controller action. This method performs all the view logic (using the data you’ve given in using the set() method), places the view inside its layout and serves it back to the end user.

For alternative views: 3.5.3.1.2 (read more)
redirect(string $url, integer $status, boolean $exit)
The flow control method you’ll use most often is redirect(). This method takes its first parameter in the form of a CakePHP-relative URL. When a user has successfully placed an order, you might wish to redirect them to a receipt screen.

function placeOrder() {

//Logic for finalizing order goes here

if($success) {
$this->redirect(array('controller' => 'orders', 'action' => 'thanks'));
} else {
$this->redirect(array('controller' => 'orders', 'action' => 'confirm'));
}
}
redirect params
The second parameter of redirect() allows you to define an HTTP status code to accompany the redirect. You may want to use 301 (moved permanently) or 303 (see other), depending on the nature of the redirect.

The method will issue an exit() after the redirect unless you set the third parameter to false.
flash(string $message, string $url, integer $pause)
Similarly, the flash() method is used to direct a user to a new page after an operation. The flash() method is different in that it shows a message before passing the user on to another URL.
flash params
The first parameter should hold the message to be displayed, and the second parameter is a CakePHP-relative URL. CakePHP will display the $message for $pause seconds before forwarding the user on.

For in-page flash messages, be sure to check out SessionComponent’s setFlash() method.
Callbacks: beforeFilter()
beforeFilter()

This function is executed before every action in the controller. It's a handy place to check for an active session or inspect user permissions.
Callbacks: beforeRender()
beforeRender()

Called after controller action logic, but before the view is rendered. This callback is not used often, but may be needed if you are calling render() manually before the end of a given action.
Callbacks: afterFilter()
afterFilter()

Called after every controller action.
Callbacks: afterRender()
afterRender()

Called after an action has been rendered.

CakePHP also supports callbacks related to scaffolding.
Callbacks: _beforeScaffold($method)
_beforeScaffold($method)

$method name of method called example index, edit, etc.
Callbacks: _afterScaffoldSave($method)
_afterScaffoldSave($method)

$method name of method called either edit or update.
Callbacks: _afterScaffoldSaveError($method)
_afterScaffoldSaveError($method)

$method name of method called either edit or update.
Callbacks: _scaffoldError($method)
_scaffoldError($method)

$method name of method called example index, edit, etc.
constructClasses
This method loads the models required by the controller. This loading process is done by CakePHP normally, but this method is handy to have when accessing controllers from a different perspective. If you need CakePHP in a command-line script or some other outside use, constructClasses() may come in handy.
disableCache
Used to tell the user’s browser not to cache the results of the current request. This is different than view caching, covered in a later chapter.
postConditions
postConditions(array $data, mixed $op, string $bool, boolean $exclusive)

Use this method to turn a set of POSTed model data (from HtmlHelper-compatible inputs) into a set of find conditions for a model. This function offers a quick shortcut on building search logic.
postConditions example
For example, an administrative user may want to be able to search orders in order to know which items need to be shipped. You can use CakePHP’s Form- and HtmlHelpers to create a quick form based on the Order model. Then a controller action can use the data posted from that form to craft find conditions:

function index() {
$o = $this->Order->findAll($this->postConditions($this->data));
$this->set('orders', $o);
}

If $this->data[‘Order’][‘destination’] equals “Old Towne Bakery”, postConditions converts that condition to an array compatible for use in a Model->findAll() method. In this case, array(“Order.destination” => “Old Towne Bakery”).
...postConditions example
If you want use a different SQL operator between terms, supply them using the second parameter.

/*
Contents of $this->data
array(
'Order' => array(
'num_items' => '4',
'referrer' => 'Ye Olde'
)
)
*/

//Let’s get orders that have at least 4 items and contain ‘Ye Olde’
$o = $this->Order->findAll($this->postConditions(
$this->data,
array('>=', 'LIKE')
));

The key in specifying the operators is the order of the columns in the $this->data array. Since num_items is first, the >= operator applies to it.
other postConditions params
The third parameter allows you to tell CakePHP what SQL boolean operator to use between the find conditions. String like ‘AND’, ‘OR’ and ‘XOR’ are all valid values.

Finally, if the last parameter is set to true, and the $op parameter is an array, fields not included in $op will not be included in the returned conditions.
paginate
This method is used for paginating results fetched by your models. You can specify page sizes, model find conditions and more. See the pagination section for more details on how to use paginate.
requestAction
requestAction(string $url, array $options)

This function calls a controller's action from any location and returns data from the action. The $url passed is a CakePHP-relative URL (/controllername/actionname/params). To pass extra data to the receiving controller action add to the $options array.
requestAction wirht return option
You can use requestAction() to retrieve a fully rendered view by passing 'return' in the options: requestAction($url, array('return'));
requestAction and caching
If used without caching requestAction can lead to poor performance. It is rarely appropriate to use in a controller or model.
requestAction in conjunction with (cached) elements
requestAction is best used in conjunction with (cached) elements – as a way to fetch data for an element before rendering. Let's use the example of putting a "latest comments" element in the layout. First we need to create a controller function that will return the data.

// controllers/comments_controller.php
class CommentsController extends AppController {
function latest() {
return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));
}
}

If we now create a simple element to call that function:

// views/elements/latest_comments.ctp

$comments = $this->requestAction('/comments/latest');
foreach($comments as $comment) {
echo $comment['Comment']['title'];
}
We can then place that element anywhere at all to get the output using:

echo $this->element('latest_comments');
more details on requestAction
3.5.3.4.6
CakePHP core components
* Security
* Sessions
* Access control lists
* Emails
* Cookies
* Authentication
* Request handling
Configuring Components
Many of the core components require configuration. Some examples of components requiring configuration are Auth, Cookie and Email. All configuration for these components, and components in general is done in your Controller's beforeFilter() method.
Configuring components with beforeFilter()
function beforeFilter() {
$this->Auth->authorize = 'controller';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');

$this->Cookie->name = 'CookieMonster';
}

Would be an example of configuring component variables in your controller's beforeFilter()>
Writing a component eg
Suppose our online application needs to perform a complex mathematical operation in many different parts of the application.

<?php

class MathComponent extends Object {
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
}

?>
Including Components in your Controllers
Once our component is finished, we can use it in the application's controllers by placing the component's name (minus the "Component" part) in the controller's $components array. The controller will automatically be given a new attribute named after the component, through which we can access an instance of it:

/* Make the new component available at $this->Math,
as well as the standard $this->Session */
var $components = array('Math', 'Session');

Components declared in AppController will be merged with those in your other controllers. So there is no need to re-declare the same component twice.
Initializing Components with Parameters
When including Components in a Controller you can also declare a set of parameters that will be passed on to the Component's initialize() method. These parameters can then be handled by the Component.

var $components = array(
'Math' => array(
'precision' => 2,
'randomGenerator' => 'srand'
),
'Session', 'Auth'
);

The above would pass the array containing precision and randomGenerator to MathComponent's initialize() method as the second parameter.
Accessing the controller instance from the component
To get access to the controller instance from within your newly created component, you’ll need to implement the initialize() or startup() method. These special methods take a reference to the controller as their first parameter and are automatically called. The initialize method is called before the controller's beforeFilter() method, the startup() method after the controller's beforeFilter() method. If for some reason you do not want the startup() method called when the controller is setting things up, set the class variable $disableStartup to true.

If you want to insert some logic before a controller's beforeFilter() has been called, you will need to use the initialize() method of the component.

<?php
class CheckComponent extends Object {
//called before Controller::beforeFilter()
function initialize(&$controller) {
// saving the controller reference for later use
$this->controller =& $controller;
}

//called after Controller::beforeFilter()
function startup(&$controller) {
}

function redir
Initialize components from a custom component
You might also want to utilize other components inside a custom component. To do so, just create a $components class variable (just like you would in a controller) as an array that holds the names of components you wish to utilize.

<?php
class MyComponent extends Object {

// This component uses other components
var $components = array('Session', 'Math');

function doStuff() {
$result = $this->Math->doComplexOperation(1, 2);
$this->Session->write('stuff', $result);
}

}
?>
Accessing models from components
To access/use a model in a component is not generally recommended; however if after weighing the possibilities this is what you want to do, you'll need to instantiate your model class and use it manually. Here's an example:

<?php
class MathComponent extends Object {
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}

function doUberComplexOperation ($amount1, $amount2) {
$userInstance = ClassRegistry::init('User');
$totalUsers = $userInstance->find('count');
return ($amount1 + $amount2) / $totalUsers;
}
}
?>