Cakephpdocs

No Category Code Examples Test Code Links Remarks
 1 cli commands cake bake [project-name] cd project-name cake bake all
 2 A menu item for CakePHP?
 3 Search Functionality It is working on individual models (or tables).
 4 User Login and Register System Need to work on it.
 5 Naming Conventions - Controller => controller name must match to a database table name; => If you decide to create controllers with names other than tables of the database, you should actually not create a controller but use a component instead. => The names of database tables as well as controllers are lowercase and in plural form. => example: orders table will have a controller php file name orders_controller.php under app/controllers folder. The controller class will follow OrdersController convention (CamelCased).
 6 Naming Conventions - Model => for orders table, the model file name under app/models directory would be orders.php. The class name would be Order extends AppModel.
 7 Naming Conventions - View => The view name will be the same as actions defined in controller. Suppose that there is an action called add (function add()), then there will be a view called add under app/views//add.ctp.
 8 Naming Conventions - table name with more than one word => For example, table name is special_orders; => then the controller file should be special_orders_controller.php under app/controllers folder; => the controller class name should be SpecialOrdersController app/controllers/special_orders_controller.php file; => the model file name should be special_order.php under app/models folder. The model class should be SpecialOrder in app/models/special_order.php file. => The view name should be the same name as an action defined in its controller under app/views/ folder.
 9 Naming Conventions - Abstraction - components If more than one controller needed to use the same actions, then you could create a component. The controllers could essentially run an include of the component and run the actions as if they were individually contained in the controller.
 10 Naming Conventions - Abstraction - elements A view to be used by multiple views is stored in what is called an element.
 11 Components Component files contain actions or functions that can be used across all the controllers. A component typically aims to provide tools to accomplish a main objective. => The file name of a component can be anything, but like models, views, and controllers, more than one word in the name must be separated by underscores and camel case when naming the class object. Including Components in the Controller with the $components Array var $components = array('Session','RequestHandler'); Running a Component Function in the Controller $user = $this->Session->read('User'); Components are not intended to work directly with the database, so the component does not do much more than return a variable, a string, or an array for the controller to use.
 12 Helpers Helpers provide functionality that is used across multiple views. Because helpers are set apart for use in the views, they are stored in the app/views/helpers directory. => example of html link helper: link('Read Post 55','/posts/view/55');?> => Radio button helper ($data is an array): radio('data');?>
 13 Elements An element contains presentation output that can be pulled into multiple view files. => Elements are named like controller actions and view files and are stored in the app/views/elements directory. => Helpers and elements differ in that helpers work with view logic, whereas elements are more like chunks of HTML that repeat throughout the views.
 14 Layouts => a layout file to be used by the entire application or one controller action at a time. => Layouts are stored in the app/views/layouts directory and contain presentation output like views and elements. They perform minimal logic and mainly serve to wrap HTML around changing views. =>A layout's file name can be anything but must be lowercase and have the .ctp extension.
 15 Behaviors => When interacting with the database, sometimes the model will need to perform more complex processes than simply CRUD functionality. In some applications, deleting a record will require performing other manipulations to other tables and records, and so on, with other database operations. Cake resolves this issue with behaviors, which are classes that may be called by models when performing model functions. => Behaviors are stored in the app/models/behaviors directory and can be named anything following the same rules for naming helper files and components. They must have the .php extension. => In the file, behavior class names are set with the following syntax: class SpecialBehavior extends ModelBehavior {} => By using behaviors to store complex or customized model operations, you give the application's models more consistency.
 16 DataSource DataSources are the files that execute functions that talk with a source that stores or supplies data to the application, such as MySql, PostgreSql, Oracle, DB2, MS Sql Server. The DataSource abstracts the sending, retrieving, saving, and deleting data to the model so that the model really behaves the same regardless of what external source processes the data. => When creating custom DataSource, make sure the file name is lowercase and has _source.php appended. An XML DataSource could be named, for example, xml_source.php and would be placed in the app/models/datasources directory. Naming the class object in the DataSource file (in this case, for the XML DataSource) is done with the following syntax: class XmlSource extends DataSource {}
 17 Naming Conventions - Do not conflict with PHP predefined function names Be Careful Using PHP Function Names as Action Names, such as date().
 18 Helpers - css link css('styles');?> will produce: => The css files should be stored under webroot/css folder.
 19 CakePHP functions - set set() function is a Cake function that assigns a value to a view variable. example: function index() { $this->set('posts',$this->Post->find('all')); }
 20 CakePHP functions - find find() function applies to the model. Example: function index() { $this->set('posts',$this->Post->find('all')); } A more detailed example: $this->Post->find('all', array('conditions'=>array('User.id'=>1), 'fields'=>'Post.name', 'order'=>'Post.id ASC', 'limit'=>10, 'recursive'=>0 ) );
 21 setting helpers array in controllers var $helpers = array('Html', 'Form');
 22 CakePHP functions - paginate() Example in controller: function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } 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 in the controller, the Paginator helper would break in the view.
 23 CakePHP functions - setFlash in Session component In controller: $this->Session->setFlash(__('Invalid Post.', true));
 24 CakePHP functions - redirect $this->redirect(array('action'=>'index')); When needing to launch another action with its views and everything else, use the redirect() function instead of requestAction(). => In short, the redirect() function causes another browser request and changes the URL, while requestAction() works internally to launch specific actions.
 25 CakePHP functions - read -- a model function In controller, read from model: $this->set('post', $this->Post->read(null, $id)); a model function, read(), which looks up the record that corresponds to the ID supplied by the user and pulls its data. 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.
 26 CakePHP functions - create - a model function In controller: $this->Post->create(); Cake performs saves through the use of the create() and save() model functions. => Initializes the model for writing a new record, loading the default values for those fields that are not defined in $data, and clearing previous validation errors. Especially helpful for saving data in loops. => Rendering
tags is simplified by the $form->create() function. This function also manages the action HTML attribute and points the form to the correct model. create( model[string], options[array] )
 27 CakePHP functions - save - a model function In controller: $this->Post->save($this->data)
 28 CakePHP functions - find('list') In controller: $users = $this->Post->User->find('list');
 29 CakePHP functions - compact This is php function: example: What does the compact() function do? It takes the array you pass into it and looks for variables of the same name as the elements in that array. It then spits out an array of key => value pairs. So, one little trick with compact() means you only have to use one set statement. This works because all those $this->set() statements simply add those values to an array.
 30 php function - get_defined_vars() for debugging After working my way through various debugging techniques, I pulled out the big gun. In my view, I dumped the output of PHP's get_defined_vars() function and found that my $vendor_type variable had been renamed to $vendorType after the following line in controller: $this->set ( compact ( 'vendor_type', 'application_type', 'states' ) );
 31 CakePHP functions - del In controller: $this->Post->del($id); // delete in posts table a row with id = $id.
 32 css - up and down arrows \2191 is for up arrow \2193 is for down arrow http://www.blooberry.com/indexdot/html/tagpages/entities/arrow.htm
 33 form helpers in view - create, input, end create('Posts');?> input('name');?> input('content', array('type'=>'textarea','rows'=>4,'cols'=>40));?> end('Submit');?>
 34 Asynchronous Sequence - AJAX Most developers refer to any asynchronous server responses as Ajax operations, even though Ajax started as an acronym meaning Asynchronous JavaScript And XML.
 35 CakePHP functions - debug() function 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:
 36 HTML helper functions - link link( title[string], url[mixed], attributes[array], confirmMessage[string], escapeTitle[bool] ) The first parameter in the HTML helper's link() function is the text to be displayed. The second parameter is the URL, following the application's routes, that will be placed in the link. example: link('

' . $post['Post'['name'] . '

', '/posts/view/' . $post['Post']['id'], null, null, false); ?> link('Add a Post','/posts/add');?> But you can use an alternate method for producing this same link by entering an array in the url parameter, like so: link('Add a Post',array('controller'=>'posts','action'=>'add'));?> Of course, entering an absolute URL into the url parameter will send the user off site: link('Check out the Bakery','http://bakery.cakephp.org');?> You can include a confirmation message to be displayed as a JavaScript alert dialog box by entering a string in the confirmMessage parameter. For instance, say you wanted to alert the user before deleting records from the database. You could do this by entering the confirm message in the $html->link() function: link('Delete','/posts/delete/'.$post['Post']['id'],null,'Are you sure you want to delete this post?');?> When this is clicked, a box will appear asking the user "Are you sure you want to delete this post?" If the user clicks Proceed, then the link will be activated. You can include HTML tags in this function by setting the escapeTitle parameter to false. Even other helper functions that output HTML can be included in the title parameter, like so: link($html->image('title.jpg'),'/',null,null,false);?>
 37 form helpers - input in checkbox in Views Example: echo $this->Form->input('Tag', array('type'=>'select', 'multiple'=>'checkbox' ) ); input( field[string], options[array] ) Perhaps no other helper function is quite so versatile as the $form->input() function. This tool works both to receive and to send data. The $form->input() Function’s Automagic Responses to Database Field Structures Field Type Returns ====== =========================== Boolean => Check box input element Date => Day, month, and year select menus Datetime => Day, month, year, hour, minute, and meridian select menus String => (for example, varchar) Text box input element Text => Text area element Time => Hour, minute, and meridian select menus Timestamp => Day, month, year, hour, minute, and meridian select menus Tinyint(1) => Check box String or text fields named => Password password, passwd, or psword Options Available for Use in the type Parameter in the options Array Option Description ==== ============================= checkbox Alias for the $form->checkbox() function date Renders select menus ordered as month, day, and year datetime Alias for the $form->dateTime() function file Alias for the $form->file() function hidden Alias for the $form->hidden() function password Alias for the $form->password() function radio Alias for the $form->radio() function select Alias for the $form->select() function text Alias for the $form->text() function textarea Alias for the $form->textarea() function time Renders select menus ordered as hour, minute, and meridian
 38 12 types of helpers in Cake Cake comes preinstalled with 12 helpers: • Ajax • Cache • Form • HTML • JavaScript • Number • Paginator • RSS • Session • Text • Time • XML http://bakery.cakephp.org
 39 To make helpers available To make the helper available, besides the HTML and Form helpers, you must specify in the controller that the helper is being used. You do this by populating the helper settings array with the corresponding helper's class name: var $helpers = array('Ajax','Session','Time'); By placing this string up by where the var $name and var $scaffold attributes are called in its controller, Cake is able to begin a new instance of the helper class object and make it available in the view.
 40 3 Basic User <-> CakePHP application interactions Users will most often interact with your Cake application in one of three ways: 1) by making a simple page request; 2) by submitting a form of some kind; 3) or by sending page or form requests asynchronously (also described as Ajax processes).
 41 CakePHP functions - requestAction - a controller function Example: $this->set('tags',$this->requestAction('/tags/getList')); requestAction can get the result of another controller action. // getList action in another (tags_controller here) controller: function getList() { return $this->Tag->find('list'); } Requesting actions as opposed to redirecting is reserved for performing logic in another controller and pulling its results to the current controller, not for simply launching another action elsewhere in the application.
 42 CakePHP functions - beforeFilter() - a controller function The beforeFilter() callback action is called before every action is executed. It is entered like any other action, as a PHP function, and interrupts processing controller logic in the requested action. To block users from accessing a certain area of the site, the beforeFilter() action can check the session for information. Example: function beforeFilter() { if ($this->action == 'view') { if (!$this->Session->check('User')) { $this->redirect('/users/login'); } } }
 43 CakePHP functions - afterFilter() - a controller function Just like the beforeFilter() callback action, afterFilter() performs logic after every action is called.
 44 CakePHP functions - beforeRender() - a controller function This callback action performs logic between the execution of the requested action's logic and the rendering of the view output for all actions. Like beforeFilter() and afterFilter(), beforeRender() can be made to apply to a specific action by using the $this->action variable.
 45 model attribute (property) - recursive function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } 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 the initial level of associations, Cake will ignore other records. The following table outlines the possible recursive values and their results. Possible Recursive Values Value Result –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
 46 CakePHP functions - find with conditions Example: $this->Post->find('all',array('conditions'=>array('User.id'=>'<> 1'))); This is somewhat similar to sql's where clause. Cake parses other SQL expressions, which include LIKE, BETWEEN, and REGEX, but you must have a space between the operator and the value. You can search for date or datetime fields by enclosing the field name in the SQL DATE() parameter. Another example: (AND case) $this->Post->find('all',array('conditions'=> array('User.id'=>1, 'DATE(Post.date)'=>'CURDATE()'))); Another example: (OR case) $this->Post->find('all',array('conditions'=>array( 'or'=>array( 'User.id'=>1,'DATE(Post.date)'=>'CURDATE()' ) ))); Another example - search multiple values of a field: $this->Post->find('all',array('conditions'=> array('User.id'=>array(1,2,5,10)) )); Another example: $this->Post->find('all',array('order'=>'date DESC', 'limit'=>5,'recursive'=>0));
 47 CakePHP functions - referer() in controller By placing $this->referer() in the URL parameter, Cake will redirect to the referring page of the current action.
 48 Where to do validations? To run a validation test, you don’t have to use the controller (in fact, you should avoid using the controller); you can run validations in the model alone.
 49 CakePHP functions - unbindModel() model function unbindModel() model function allows you to temporarily kill the "has and belongs to many" relationship. Example: $this->unbindModel( array('hasAndBelongsToMany'=>array('Tag')) );
 50 CakePHP functions - bindModel() model function The bindModel() allows you to assign associations as well. Example: $this->bindModel( array('hasManyAndBelongsToMany'=>array('Tag')) );