recursive in CakePHP

The recursive property defines how deep CakePHP should go to fetch associated model data via find(), and read() methods.

Imagine your application features Groups which belong to a domain and have many Users which in turn have many Articles. You can set $recursive to different values based on the amount of data you want back from a $this->Group->find() call:

  • -1 CakePHP fetches Group data only, no joins.
  • 0 CakePHP fetches Group data and its domain
  • 1 CakePHP fetches a Group, its domain and its associated Users
  • 2 CakePHP fetches a Group, its domain, its associated Users, and the Users’ associated Articles

Ajax request in cakephp 2.x

show.ctp

<?php echo $this->Html->script('jquery', FALSE); ?>

<?php

echo $this->Form->create('Count', array('action'=>'ajaxShow'));
echo $this->Form->input('field', array('id'=>'field'));
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));

?>

<div id='sending' style="display:none"> Counz[dot]gif will be displayed </div>
<div id='success'></div>

controller

var $name = 'count';

    public $helpers = array('Js' => array('Jquery'));
    //var $helpers = array('Ajax', 'Javascript');
    var $components = array('RequestHandler');
public function ajaxShow(){
         $this->layout = 'ajax'; 
        if($this->RequestHandler->isAjax()){  
            $this->render('success', 'ajax');
        }else{
            $this->set('for_map', $this->count->find('all'));

        }
    }

success.ctp

<p>It's working</p>

Controller Attributes in CakePHP

property Controller::$name

The $name attribute should be set to the name of the controller. Usually this is just the plural form
of the primary model the controller uses.

$components, $helpers and $uses

The next most often used controller attributes tell CakePHP what $helpers, $components, and
models you’ll be using in conjunction with the current controller. Using these attributes make
MVC classes given by $components and $uses available to the controller as class variables
($this->ModelName, for example) and those given by $helpers to the view as an object reference
variable ($this->{$helpername}).

property Controller::$uses
Controllers have access to their primary model available by default. 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.
If you do not wish to use a Model in your controller, set public $uses = array(). This will
allow you to use a controller without a need for a corresponding Model file. However, the models
defined in the AppController will still be loaded. You can also use false to not load any
models at all. Even those defined in the AppController.

property Controller::$helpers
The HtmlHelper, FormHelper, and SessionHelper are available by default, as is the SessionComponent. But if you choose to define your own $helpers array in AppController, make sure to include HtmlHelper and FormHelper if you want them still
available by default in your Controllers. To learn more about these classes, be sure to check out their
respective sections later in this manual.

property Controller::$components
The components array allows you to set which Components a controller will use. Like $helpers
and $uses components in your controllers are merged with those in AppController. As with
$helpers you can pass settings into $components. See Configuring Components for more infor-
mation.

Other Attributes
While you can check out the details for all controller attributes in the API3 , there are other controller at-
tributes that merit their own sections in the manual.
property Controller::$cacheAction
The cacheAction attribute is used to define the duration and other information about full page caching.
You can read more about full page caching in the CacheHelper documentation.
property Controller::$paginate
The paginate attribute is a deprecated compatibility property. Using it loads and configures the
PaginatorComponent. It is recommended that you update your code to use normal component

Request Life-cycle callbacks in CakePHP

CakePHP controllers come fitted with callbacks you can use to insert logic around the request life-cycle:
Controller::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.
Note: The beforeFilter() method will be called for missing actions, and scaffolded actions.
Controller::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.
Controller::afterFilter()
Called after every controller action, and after rendering is complete. This is the last controller method
to run.
In addition to controller life-cycle callbacks, Components also provide a similar set of callbacks.

common tasks people learning CakePHP

These are common tasks people learning CakePHP usually want to study :
1. Layouts: Customizing your website layout
2. Elements: Including and reusing view snippets
3. Scaffolding: Prototyping before creating code
4. Code Generation with Bake: Generating basic CRUD code
5. Simple Authentication and Authorization Application: User authentication and authorization tutorial

 

 

Data Validation in cakePHP

alidation rules are defined in the model.

class Post extends AppModel {
public $validate = array(
‘title’ => array(
‘rule’ => ‘notEmpty’
),
‘body’ => array(

‘rule’ => ‘notEmpty’
)
);
}

 

The $validate array tells CakePHP how to validate your data when the save() method is called.

 

 

CakePHP conventions

constroller:
Controller class names are plural, CamelCased, and end in Controller.
ex: PeopleController and LatestArticlesController

URL Considerations for Controller Names:
single word controllers map easily to a simple lower case URL path.
ex: ApplesController is accessed from http://example.com/apples

File and Class Name Conventions:
The Controller class KissesAndHugsController would be found in a file named KissesAndHugsController.php
The Component class MyHandyComponent would be found in a file named MyHandyComponent.php
The Model class OptionValue would be found in a file named OptionValue.php
The Behavior class EspeciallyFunkableBehavior would be found in a file named EspeciallyFunkableBehavior.php
The View class SuperSimpleView would be found in a file named SuperSimpleView.php
The Helper class BestEverHelper would be found in a file named BestEverHelper.php

Model and Database Conventions:
Model class names are singular and CamelCased.
ex: Person, Post, User, CountyState, and PostsTags
Table names corresponding to CakePHP models are plural and underscored.
ex: people, posts, users, country_states, and posts_tags
Field names with two or more words are underscored
ex: first_name, last_name, user_name

View Conventions:
The getReady() function of the PeopleController class will look for a view template in /app/View/People/get_ready.ctp

 

_________________________________________________________________________________________

Database

Database tables are plural: “comments” or “user_comments” etc.

I recommend to stick to conventions and underscore + lowercase all table fields: “last_login” (instead of “lastLogin” or even worse “last login”) etc.

Models

Model names are singular and camelCased: “Comment or “UserComment” filename: “comment.php” or “user_comment.php”

Controllers

Model names are plural and camelCased: “Comments or “UserComments” filename: “comments_controller.php” or “user_comments_controller.php”

Controller actions should be underscored! “function admin_import_from_xml(){}”

Views

Views have an own folder for each controller – plural: “comments” or “user_comments”. Inside are the templates for the specific actions- underscored. filenames for example: “index.ctp” or “admin_index.ctp” (with prefix admin) or “admin_order_entries.ctp”

Libs

As long as namespaces are not an issue, they might conflict with existing model classes (they have no “Model” appended!) and other cake core classes or even some vendor files. I recommend to use the controller syntax here: Name – camelcased: “GoogleTranslateLib” filename: “google_translate_lib.php”

This way it won’t interfere with any Google class – or “FileLib” won’t interfere with core “File” class.

Behaviors

Name – camelcased: “GeoPlugin” filename: “geo_plugin.php”

They should not be similar to model names. Otherwise they might interfere with existing models. So use adjectives, verbs or plural names: “Ratable”, “Geocoded”, “Configurations”, …

Components

Name – camelcased: “GoogleTranslateComponent” filename: “google_translate.php”

They could interfere with models (and maybe behaviors). So it might make sense to use plural forms or forms that are not likely to be a model name.

Helpers

Name – camelcased: “GoogleHelper” filename: “google.php”

With the new 1.3 “$this->Helper” style they can now be anything you want. With a little modification of the core, at least. I like to call my helpers “MyHelper” if there are specific to a controller/module and it is not yet a plugin. Example: Conversations controller + Conversation model + MyConversation helper (as it is only needed inside this specific controller). Other helpers like “GoogleMap” might be used in several controllers, for instance.

Plugins

They should not be similar to controller names. Otherwise they might interfere with existing controllers. So use adjectives, verbs or singular names: “Rating”, “Setup”, “Configuration”, …

Constants

No matter if they are class constants or global constants, they are always uppercase and underscored: “MIN_USER_AGE” etc.

Variables

camelBacked: $userComment

The first letter is uppercase if the variable represents an object: $File = new File(); $GeoPlugin = new GeoPluginLib();

Layout/Script

CSS classes/ids: I use camelBacked style here, too: <div id="someId"></div> But thats purely a matter of taste. I like to use it in IDs because I can easily attach “-x” (the record id) and split it afterwards on “-” to get the record id in JS: … id=”someId-2″… comes in handy sometimes

Test Cases

Same as the original file – only with “.test” appended to it: “google_translate_lib.test.php” for instance.

How to create custom MySQL queries in CakePHP?

Location Controller should be:

loadModel(“Location”);
$this->LocationModel->getLocations(); // I will strongly discourage using get()
}
}

Location Model should be:

query(“SELECT * FROM locations;”); // if table name is `locations`
return $this->query(“SELECT * FROM Location;”); // if table name is `Location` since your public name is `Location`
}
}