Model: Handles all database functions, app/models/ {Model name}.php
View: Handles the presentation layer and displays, app/views/ {Controller
Including Ajax output name}/ {View name}.ctp
Controller: Handles all logic and requests app/controllers/ {Controller
Name} _controller.php
-First Decide which application you want make
-i.e i am going to make add/update/delete for items
-1.Create table name with “items”.all letter should be lowercase.(its plural name)
-2.Create item.php file in model folder .all letter should be lower(its singular name)
-3.Create items_controller.php file in controller folder .all letter should be lower and filename=items+”_controller” (its plural name).
4. Chaptor -4
In general, filenames are underscored while classnames are CamelCased. So if you have a class MyNiftyClass, then in Cake, the file should be named my_nifty_class.php. Below are examples of how to name the file for each of the different types of classes you would typically use in a CakePHP application:
Each file would be located in or under (can be in a subfolder) the appropriate folder in your app folder.
Model classnames are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.
Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.
Foreign keys in hasMany, belongsTo or hasOne relationships are recognized by default as the (singular) name of the related model followed by _id. So if a baker hasMany cakes, the cakes table will refer to the baker in the bakers table via a baker_id foreign key.
Join tables, used in hasAndBelongsToMany (HABTM) relationships between models should be named after the model tables they will join in alphabetical order (apples_zebras rather than zebras_apples).
All tables with which CakePHP models interact (with the exception of join tables), require a singular primary key to uniquely identify each row. If you wish to model a table which does not have a single-field primary key, such as the rows of your posts_tags join table, CakePHP’s convention is that a single-field primary key is added to the table.
CakePHP does not support composite primary keys. If you want to directly manipulate your join table data, use direct query calls or add a primary key to act on it as a normal model. E.g.:
CREATE TABLE posts_tags (
id INT(10) NOT NULL AUTO_INCREMENT,
post_id INT(10) NOT NULL,
tag_id INT(10) NOT NULL,
PRIMARY KEY(id));
Controller classnames are plural, CamelCased, and end in Controller. PeopleController and LatestArticlesController are both examples of conventional controller names.
The first method you write for a controller might be the index() method. When a request specifies a controller but not an action, the default CakePHP behavior is to execute the index() method of that controller. For example, a request for http://www.example.com/apples/ maps to a call on the index() method of the ApplesController, whereas http://www.example.com/apples/view/ maps to a call on the view() method of the ApplesController.
You can also change the visibility of controller methods in CakePHP by prefixing controller method names with underscores. If a controller method has been prefixed with an underscore, the method will not be accessible directly from the web but is available for internal use. For example:
<?php
class NewsController extends AppController {
function latest() {
$this->_findNewArticles();
}
function _findNewArticles() {
//Logic to find latest news articles
}
}
?>
10. }
11. ?>
As you’ve just seen, single word controllers map easily to a simple lower case URL path. For example, ApplesController (which would be defined in the file name ‘apples_controller.php’) is accessed from http://example.com/apples.
Multiple word controllers can be any ‘inflected’ form which equals the controller name so:
will all resolve to the index of the RedApples controller. However, the convention is that your urls are lowercase and underscored, therefore /red_apples/go_pick is the correct form to access the RedApplesController::go_pick action.
View template files are named after the controller functions they display, in an underscored form. The getReady() function of the PeopleController class will look for a view template in /app/views/people/get_ready.ctp.
The basic pattern is /app/views/controller/underscored_function_name.ctp.
By naming the pieces of your application using CakePHP conventions, you gain functionality without the hassle and maintenance tethers of configuration. Here’s a final example that ties the conventions
Using these conventions, CakePHP knows that a request to http://example.com/people/ maps to a call on the index() function of the PeopleController, where the Person model is automatically available (and automatically tied to the ‘people’ table in the database), and renders to a file. None of these relationships have been configured by any means other than by creating classes and files that you’d need to create anyway.
Now that you’ve been introduced to CakePHP’s fundamentals, you might try a run through the CakePHP Blog Tutorial to see how things fit together.
A good web application that illustrates Cake’s rapid development functionality and table associations
is a blog. Here, you will build a simple blog application using the scaffolding feature
to test associations. Later, you’ll expand the blog to take on more powerful features. Mastering
table associations and how they work in Cake is essential for pulling in advanced features that
matter for complex web sites. A simple blog application will help us discuss table associations
in an easier way and should help you if you’re unfamiliar with table associations to be better
equipped to use Cake.
“Belongs To”
When associating tables, you need to tell Cake what type of relationship each table has with the others. This blog will have a “belongs to” relationship in a couple of tables. First, since each blog post will have an assigned author, each blog post “belongs to” one user. In other words, the posts table “belongs to” the users table. You have placed a user_id field in the posts table
as a way to save this relationship. For each record in the posts table, one of the records from the users table will be saved by assigning one of its IDs to user_id.
1 <?
2 class Post extends AppModel {
3 var $name = ‘Post’;
4 var $belongsTo = array(‘User’);
5 }
6 ?>
Line 4 of Listing 4-4 shows how to enter a “belongs to” relationship in Cake. You do this by assigning an array of models that are part of the relationship to the current model. The class object variable Cake uses to build “belongs to” relationships is the var $belongsTo attribute. In any Cake application, “belongs to” relationships are made by following the code on line 4. You can add relationships by including them in the array syntax.
className Parameter :-
A possible key to be included with the $belongsTo settings is className. Simply put, className is the model to which the current model belongs. In this case, it would be set to User, meaning the class name of the users table’s model. If you decide to abandon Cake’s model naming conventions or if there is a complex reason for naming a model other than the standard Cake convention, then you will need to specify the name in this setting; otherwise, Cake will not be able to link the association on its own.
foreignKey Parameter:-
This key sets the foreign key found in the related model. This setting is useful for specifying multiple “belongs to” relationships.
conditions Parameter :-
This key contains a SQL string that filters related model records. Generally, it will contain an equals/not-equals SQL statement for a field (for example, Post.published = 1).
fields Parameter:-
By default, Cake will return all fields from the associated table. In this case, all fields from the User record, which is associated with the current post, will be fetched and made available to the Post model. You can limit this by using the fields key. You can set these keys to your own values by assigning them as an array to each item in the $belongsTo array. Listing 4-5 shows the Post “belongs to” relationship with all keys displayed.
var $belongsTo = array(
‘User’=>array(
‘className’=>’User’,
‘foreignKey’=>’user_id’,
‘conditions’=>null,
‘fields’=>null
)
);
“Has One”
Each relationship with association mapping must be specified in both directions. In other words, just saying that posts belong to users is not enough. You must also specify in the User model how users are associated to any other table. In this case, a user will “have many” posts.Three relationships are possible—“has one,” “has many,” and “has and belongs to many.” First I’ll discuss the “has one” association.
This relationship is exactly a one-to-one relationship. In applications that assign profiles to users, such as social networking web sites, the “has one” relationship is used. Each user has one profile, and one profile belongs to just one user.
To establish the “has one” relationship, you set the $hasOne attribute like you did with $belongsTo in the Post model (see Listing 4-6).
Listing 4-6. The $hasOne Attribute String That Sets a “Has One” Relationship in the UserModel
var $hasOne = array(‘Post’);
className Parameter :
For a “has one” relationship, className should always be set to the model that contains the belongsTo attribute pointing to the current model.
foreignKey, conditions, and fields Parameters:
These are similar to the “belongs to” foreignKey, conditions, and fields parameters. Set them to add more specific control to the “has one” relationship.
dependent Parameter:-
When deleting records in a “has one” relationship, you may want both sides of the association to be deleted. For example, when a user has one profile and the user is deleted, you may want the associated profile to be deleted also. In these cases, the dependent key allows you to do this easily. By default, it is set to false. Set dependent to true to delete records in both tables when the delete action is run through the associated model.In the blog you are building, you have no need of a “has one” relationship. We will make use of another important relationship in Cake: “has many.”
“Has Many”
You’ve created the Post model; it’s time to make the User model. Create the User model in the app/models directory and work in the code shown in Listing 4-7.
Listing 4-7. The UserModel
1 <?
2 class User extends AppModel {
3 var $name = ‘User’;
4 var $hasMany = array(‘Post’);
5 }
6 ?>
For your blog, each user will have many posts. Even if a user enters only one post, you would still want the relationship to be capable of saving more than one post per user. By telling the User model that multiple post records are associated with it, and by completing the relationship in the Post model with the belongsTo attribute, Cake can now link the two together. For more control, you may want to enter more parameters for the “has many” relationship.
className, foreignKey, conditions, and fields Parameters
These parameters specify the same things as described in the “belongs to” relationship earlier.
dependent Parameter
This setting behaves similarly to how it is described for the “has one” relationship. In the “has many” relationship, setting dependent to true will work recursively. In other words, if you set the $hasMany attribute in the User model to dependent=>true, then whenever a user is deleted, all posts ever assigned to that user will be deleted as well.
order Parameter
You can control the sorting order of the associated records by entering SQL syntax in this parameter. For example, in the User model, you could set order to Post.datetime ASC, and it would order all associated posts by their date and time in ascending order.
limit Parameter
Some database requests may return a substantial number of associated records. You may want to limit the number of returned records to cut down on server load time. You can do this by setting this parameter to a value representing the maximum number of associated records Cake will fetch from the database.
finderQuery Parameter
To produce even more customized results, you may enter a SQL string in the finderQuery key, and it will run when the associated records are queried. You really should need to use this option only if your application requires a high level of database customization. Most of the time, you will be able to work just fine using Cake’s built-in model functions.
The “has many” relationship is extremely useful for helping to design effective databases.
If you know that you intend to put a select menu in your application for a series of options
that will be stored in the database, the “has many” relationship can help you do so without
writing a static list in HTML. Instead, you could build a table to store those options and associate
them through the models using a “has many” relationship. Then, no matter what may
happen with feature creep or with adding or deleting options from the list, you can rest
assured the application isn’t broken and can handle the changes. It’s built on a database, not on static forms, meaning that the application is dynamic and can change easily.
“Has and Belongs to Many”
The final association Cake can recognize for database table relationships is the “has and belongs to many” relationship. This relationship is powerful but also a little difficult to master. The more you experiment with “has and belongs to many” associations, the easier it will be to use them in your applications.In short, I’ve already discussed a one-to-one relationship with the hasOne association, and
the hasMany association shows you how a one-to-many relationship is managed in Cake. What about a many-to-many relationship?
Many-to-Many Relationships in Cake
Many web sites use tags to order their content. Many blogs, rather than assigning one category to a post, will have a list of tags that can be assigned multiple times to multiple stories, and vice versa. This is a many-to-many relationship between posts and tags. One post can have many tags, and each tag can belong to many posts.
Structurally, the database can handle many-to-many relationships only if there is a third table that saves these associations. In the post-to-tag example, a third table named something like posts_tags would be created. In it would be just two fields: post_id and tag_id. By having a third table, you maintain the flexibility needed to list as many relationships as the application would need to save; there is no limit to the number of associations in either direction because the third table can continually save more records.As you can imagine, Cake saves a great deal of time in managing this association. Just like the $hasOne and $hasMany attributes, you create a “has and belongs to many” association by entering the $hasAndBelongsToMany attribute in the model.You can also test “has and belongs to many” associations in the scaffold. Rather than view a select menu for a one-to-many relationship, Cake’s scaffolding will render a multiple-select
menu. In this way, you can test the association in the same manner that you tested the “has many” relationship earlier.
Chapter -5
Usefull link http://www.archive.org/details/SettingUpTheCakephpConsoleOnWindows
Please read this chaptor for create model/view/controller file from command prompt
1.please set environment variable to path(my computer/right click/advance/environment variable/select path/edit)
2.type after ;C:\wamp\php;C:\wamp\www/cakep\cake\console
3.run command prompt .
4. goto at c:\wamp\php
5. type cake bake command
6.after created app folder in your desire folder typ
-cake bake –app ~/Sites/blog/app/
7 same for othe command for example acl
-cake acl –initdb app ~/Sites/blog/app/
Chaptor -6
Handling User Interactions
In general, three kinds of sequences result from a user interacting with a Cake application:
• A simple page request sequence
• A formsubmission sequence
• An asynchronous (Ajax) sequence
the first step for adding a new record is to create a new row with the create()
model function, and the second step is to save $this->data by passing it through the save()
model function.
Using the Debug Function
Often you will want to view the contents of these data arrays. Cake’s debug() function provides
a detailed and nicely formatted view of a specified array. In this view file, insert the following
line, which uses the debug() function:
Chapter -7
Recursive
Line 2 of Listing 7-3 sets the Post model’s recursive attribute to 0. This attribute affects how Cake pulls data from the table. Remember that posts are associated with tags and users. When the Post model runs a query to pull posts from the database, it will also fetch associated records from the tags and users tables. The recursive attribute tells the model how far to look when pulling those associated records. If users were to have an association with another table and the recursive attribute were set to a value greater than 1, then the model would pull not only the associated user records but their associated tables’ records as well.In the Index action, the recursive attribute is set to zero, which means that beyond theinitial level of associations, Cake will ignore other records. Table 7-1 outlines the possible
recursive values and their results.
–1 Returns only the current model and ignores all associations
0 Returns the current model plus its owner(s)
1 Returns the current model and its owner plus their associated models
2 Returns the current model, its owner, their associated models, and the associated
models of any associations
Pagination
Line 3 of Listing 7-3 uses the paginate() controller function. This allows the Paginator helper to simplify column sorting and multiple pages of data. Essentially, the paginate() function performs a find() model function but also analyzes the result and passes some important pagination parameters to the view. Then, in the view, the Paginator helper takes those parameters and constructs multiple pages and column sorting. If the paginate() function is not run n the controller, the Paginator helper would break in the view. If pagination is an important element of the application, then leave the paginate() function here. However, for this blog,I will remove the Paginator helper from the view, so the paginate() function can also be
removed from the Index action.
The find() Function
You can actually cut down the code for the Index action by using the find() function instead of paginate(), as shown in Listing 7-4.
type ‘first’ Can be all, first, or list; determines what type of find
operation to perform
conditions null Array containing the find conditions as key and value
fields null Array specifying from which fields to retrieve data
order null Ordering conditions; used to specify by which field to order the
result set; field name must be followed by either ASC or DESC
page null Page number for using paged data
limit null The limit of results to be calculated per page
offset null The SQL offset value
recursive 1 Recursive value for associated models; can be overridden by the
recursive attribute
The read() Function
In short, the read() function reads the contents of a particular record. It differs from find() in
that it does not include the recursive parameter. See Table 7-3 for parameters available in the
read() model function.
fields Mixed null String value for a single field name or an array of field
names
id Integer null ID of record to be read
The setFlash() Function
In Chapter 6 I discussed the setFlash() function, but only in basic terms. This function can go
beyond displaying a mere error message.
message String null The message to be made available in the $session->
flash() function in the layout
layout String default The layout in which to place the flash message; this can
switch the <div> container element in which the flash is
displayed from the default to another customized one
params Array null Parameters to be passed to the layout as view variables
key String flash A way to distinguish various flash message types for
multiple flash messages.
Validating Data
Perhaps one of the most cumbersome tasks in web development is running data validation
tests on user-submitted forms
var $validate = array(
‘name’=>’alphaNumeric’,
‘date’=>’date’,
‘content’=>null
);
Trimming Results
Imagine that you ran the same query used in the previous section but for a large database with thousands of stored records. All the associated models would get pulled into the array and make for a substantially large process. Early on you won’t notice the load your customized code could impose on the server, because you’re usually dealing only with test data and in low quantities. But what if you were to launch the application on an extremely busy web site? Quite possibly the application could overload the server when searching for all the associations. For this reason, Cake has provided some functions that can help trim results by killing associations on the fly.
The unbindModel() Function
In Listing 7-11, several lines of code were returned to describe the associated models in the array. Remember, this is just one record. All these lines would be multiplied not only by the number of records returned but also by how many associated tags are assigned to each record.There’s a possibility of loading redundant data, especially when you run queries on “has and
belongs to many” associations.The unbindModel() model function allows you to temporarily kill the “has and belongs to many” relationship the Post model shares with the Tag model. In the findByYear() function in the Post model, you can run this function before the database query, and the results will change dramatically. Listing 7-12 shows how to insert this function in the findByYear()
function.
Listing 7-12. Using the unbindModel() Function to Trim Results and Server Load
1 function findByYear($year=null) {
2 $date = $year.’-01-01 00:00:00′;
3 $end_date = $year.’-12-31 23:59:59′;
4 $this->unbindModel(array(‘hasAndBelongsToMany’=>array(‘Tag’)));
5 return $this->find(‘all’,array(‘conditions’=>array(‘DATE(Post.date)’=>å
‘>’.$date,’DATE(Post.date)’=>’<’.$end_date)));
6 }
The bindModel() Function
Just as the unbindModel() function helps you kill associations on the fly, the bindModel() allows you to assign associations as well. Again, this function operates for just one query and then ceases to affect other succeeding model functions.
This function follows the same syntax as the unbindModel() function and contains two arrays: one for the association to be bound to the current model and another for the models to be assigned to the association.
Chapter -8
Using the Ajax Helper
Cake comes standard with the Ajax helper—a nifty set of methods for simplifying the code you enter in the view to make Ajax requests work properly. Like other helpers, it has more than a dozen useful functions (see Table 8-1) that can be called to reduce a process usually to a single string.
Table 8-1. Functions in the Ajax Helper
Function Description
afterRender() Includes code blocks after a view has been rendered
autoComplete() Creates an autocomplete text field
div() Creates a <div> element for Ajax updates
divEnd() Closes an Ajaxed <div> element
drag() Creates a draggable element; requires the Scriptaculous animation libraries
drop() Creates a droppable element; requires Scriptaculous
dropRemote() Creates an area that triggers an Ajax response when a draggable is dropped
onto it
editor() Creates an editor control that is swapped for the element when triggered by
the user; requires Scriptaculous
form() Creates a form element that runs in the background when submitted
isAjax() Returns true if the current request is a Prototype update
link() Creates a link to run an Ajax call
observeField() Triggers an Ajax response when the observed field is changed
observeForm() Observes a form and triggers an Ajax response when changed
remoteFunction() Creates Ajax functions to be run, usually in conjunction with a link() event
remoteTimer() Triggers an Ajax response at a specified time interval
slider() Creates a slider control; requires Scriptaculous
sortable() Makes lists or other objects sortable; requires Scriptaculous
submit() Renders a form submit button that triggers an Ajax form submission
Chapter – 8
Using an Ajax Form
Now after line 14 in the app/views/posts/view.ctp file, you can include a form for adding
comments. When doing so, you’ll use the Ajax helper so that when the user submits a comment,
it updates the <div id=”comments”> element without refreshing the whole screen.
To work Ajax into this view, insert the Ajax form shown in Listing 8-7 into the view file.
Listing 8-7. The Add Comments Form
15 <?=$ajax->form(‘/comments/add’,'post’,array(‘update’=>’comments’));?>
16 <?=$form->input(‘Comment.name’);?>
17 <?=$form->input(‘Comment.content’);?>
18 <?=$form->input(‘Comment.post_id’,array(‘type’=>’hidden’,'value’=>å
$post['Post']['id']));?>
19 <?=$form->end(‘Add Comment’);?>
The $ajax->link() function has been included in lines 14 and 15. It behaves similarly to the
$html->link() function used in baked views
Chapter -9
Installing Helpers
You have already used some built-in helpers and made them available to the application by entering their names in the var $helpers array in the controller or App controller. When installing third-party helpers or creating your own, you must take the following steps to ensure the helpers work properly:
1. Every helper file should go in the app/views/helpers directory.
2. Include the helper’s class name in the var $helpers array in either the App controller or in a specific controller in whose views the helper may be called.
3. When using the helper in the view, make sure you call the helper’s class object correctly (that is, use the $ajax variable to call the Ajax helper object). Don’t create local variables in the view that might conflict with available helper objects.
Chapter- 10
Remember that the routes.php page is cascading, meaning that the order of routes matters. If Cake resolves a URL with one route, it will immediate end there and not proceed to check other routes down the page. Although this generally doesn’t affect the overall application, it can make a difference if you are working with more complex routes that occur in the same controller or action.
Chapter-11
Why Use Components?
But you may ask, why have components when there’s an App controller? Shouldn’t the App controller hold all the functions used by multiple controllers? Yes and no. The App controller does hold more generalized actions, or actions that more than one controller will use. Rather than employ the requestAction() function to allow a controller to access a function in another controller, you could just place the function in the App controller and scale it to be brought across the application into multiple controllers.Consider the actions in the App controller like you consider display elements in the layout; parts of the view that you want to be visible across all views. Multiple views should be placed in a layout, and in a similar way, actions that will be used across controllers should be placed in the App controller. However, there are still helpers for the views that are used for specific display output tasks. The $html->link() helper function, for example, can be used only in the view because it generates HTML output, but being repeated throughout multiple views, it makes sense to house this function in a helper file rather than in the layout or in the
controller. Components serve a similar purpose in Cake applications in the sense that they house specific functions that the controller or multiple controllers can use.
For example, consider the built-in components in Cake. Some of these are the Auth,
Session, and RequestHandler components. Their functions all serve to specifically help the controller perform actions relating to their specific method; actions in the authentication component all have to do with helping the controller manage user authentication processes,and so forth. In a sense, helpers are portable view functions in that they can be distributed and pulled into any Cake application and work in a specific way to enhance and simplify the processes the views may need. Similarly, components are portable controller functions that serve a specific purpose and can be distributed to any controller in any Cake application.
Other Components
Cake’s built-in components certainly cut down on the amount of code needed to run common web application methods. Not only does it include the components discussed earlier, but it also includes others that are more advanced: the ACL (which stands for “access control list”), RequestHandler, and Security components.
ACL One of the most complicated methods for building web applications is access control for multiple users. The Auth component takes care of simple authentication, but what if you wanted to have multiple layers for users and their access levels? Or, better yet, what about dynamically altering a user’s privileges across the site? This more complex system for assigning areas for the user requires access control lists that outline a tree or matrix of who gets access to what areas in the site. The ACL component simplifies this type of user management with an assortment
of functions and methods.
RequestHandler This component helps with managing HTTP requests and obtaining more client-side information. Features such as SSL detection, reading the type of HTTP request, and responding with a unique MIME type give the RequestHandler a lot of power for making your web application
accessible to more than one type of user. For instance, web services can be managed with the RequestHandler, which allows for other web sites to access information and talk to your application. The RequestHandler can also output information as a MIME type other than text/html, which allows your application to even work in nonbrowser client applications.
Security The Security component provides ways for tightening up the security of the web application and avoiding vulnerabilities. Together with the Auth component, Security can provide extra
mechanisms for checking user authentications and also display more complex error messages depending on how the user interacts with the application. You can require that certain actions run only under an SSL-secured request or hash strings with this component. By sticking to secure methods for building your applications and by running the Security component to protect the site, you more effectively prohibit unwanted intrusions or other attacks.
Utility Classes
Configure
File and Folder
HTTP Socket
Localization and Internationalization
Third-Party Components
Cake’s built-in components and utilities are extremely helpful in extending the functionality of the controller and model. Even more components are available online through Cake’s open source service CakeForge (www.cakeforge.org) and the Bakery (http://bakery.cakephp.org).These third-party components cover all sorts of functions that can reduce the amount of code you need to write. When running components, remember to follow the instructions supplied by the developer, which usually assume you know how to install a component (which was covered
in “Using Components” earlier). Third-party components available at the Bakery include Twitter, Image Resizer, LastRSS, SMS Text, Authorize.net AIM Integration, and Yahoo! Weather. Searching for components first before trying to write a long controller process yourself can yield excellent results.
Chapter-12
Using Vendors
Simply put, a vendor is a non-Cake script of some kind. For example, let’s say you want to include a snazzy PHP class script you found on the Internet that simplifies generating CAPTCHA1 images. You can assume that the developer was not thinking of CakePHP specifically when building the script, so its functions and classes won’t be structured to work in Cake. No problem—you just have to bring the script into the application as a vendor.
The first step is to place the PHP script into the app/vendors folder. By doing so, you
make the script available to the Cake application while keeping all the vendors in one place.
You won’t need to rename the file to fit Cake’s conventions.