CakePHP 21 tips you must know

Source: Internet
Author: User
CakePHP: article is the most classic of CakePHP. Although it is not a complete hands-on series, The Author will use CakePHP's CakePHP you must know 21 tips


This article is the most classic in the CakePHP tutorial. Although it is not a complete hands-on series, I have summarized 21 articles about my use of CakePHP, which are especially useful to new users.

During translation, some special words in CakePHP are intentionally reserved without translation, such as controller and model. I believe that people who have learned CakePHP should be able to understand what they mean immediately.

In addition, the wiki of CakePHP has expired and is replaced by a website named bakery. The wiki links referenced in the original text have also been updated to bakery.

Quick creation of static pages

I want to create several pages that only contain static data. the default layout is used and no model is required. Initially I tried to create a controller and define an action for each static page. However, this method is clumsy and is not suitable for creating static pages quickly.

In fact, you only need to use pages controller to create a view under the views/pages folder and access it through/pages. For example, I created/views/pages/matt. thtml to access it through a


Change the static page title

To change the page title when using pages controller, add the following code to view:

 pageTitle = 'Title of your page.'; ?>


Send data to layout on the static page

To pass data to layout (for example, to indicate which part of the navigation bar should be highlighted), you can add the following code to view:

 _viewVars['somedata'] = array('some','data'); ?>

This array can be accessed through $ somedata in layout.


Quickly create backend management

If you need to create a background management program and want all management actions to be located in a specific folder, open config/core. php and remove the following line of comments:

define('CAKE_ADMIN', 'admin');


In this way, all actions starting with "admin" can be accessed through/admin/yourcontroller/youraction. For example, if an action named "adminadd" is created in posts controller, you can access this action through In this way, you can easily set a password for the admin directory to avoid arbitrary access by others.


View the SQL statements executed in the background

You only need to change the DEBUG constant in config/core. php to view the SQL statements executed in the background. 0 indicates the product level, 1 indicates the development level, 2 indicates the complete SQL debugging, and 3 indicates the complete SQL debugging and displays the object data. I usually set DEBUG to 2 so that a table containing SQL debugging information is displayed at the bottom of each page.

If the table added at the bottom of the page breaks the page layout (especially when Ajax is used to obtain the page and display it in the middle of the page rather than the bottom), you can add the following code in CSS to hide debugging information:

#cakeSqlLog { display: none; }

In this way, the page layout can be maintained, and debugging information can be viewed by viewing the source code. Of course, do not forget to change the debugging level back to 0 when releasing the website.


Obtain rich development documents

Don't always stare at the manual. Wiki and API are also invaluable. The development guide in wiki is very useful, and the API documentation looks difficult at the beginning, but you will soon find that the information here is very important for you to create a CakePHP website.


Use bake. php

Bake is a command line PHP script that can automatically generate model, controller, and view based on the database. At the initial stage of development, I strongly recommend using scaffolding to run your prototype program. But if you know clearly that scaffolding is not suitable, I recommend you use bake. Bake generates all the files and saves them to the disk so that you can modify them at will. This saves the effort of creating associations, views, and basic CRUD crollder operations.

(Note: four basic operations for CRUD-Create, Read, Update, Delete, and database applications, namely "add, query, modify, and Delete ".)

Bake is very convenient. You only need to create a table in the database and execute php bake. php in the/cake/scripts/directory.

If you run bake in interactive mode, it prompts you to create a model, controller, and view in several steps. After the creation, I usually read all generated code and make necessary modifications.


Pay attention to permissions when releasing a program

Once, when I published a program, I packed the entire cake directory and uploaded it to the server with scp. Once debugging information is disabled, an error occurs. database calls cannot return any data. I have nothing to worry about, because I have to pass the debugging information to debug the problem. Someone told me later that/app/tmp should be writable to apache. After the permission is changed to 777, the problem is solved.


Complex model verification

I need to perform more complex verification, instead of simply verifying that the input box is not empty or conforms to a regular expression. For example, I want to verify that the email address used during user registration is in use. On the wiki, I found this article on advanced verification, which mentions some useful advanced verification methods.


Record error logs

$this->log('Something broke');

In this way, the error is recorded in/tmp/logs/(I initially thought it would be recorded in apache's error log ).


Allow the controller to use other models

If your controller needs to call data from different models, use the following code at the beginning of controller:

class yourController extends AppController {  var $uses = array('Post','User');}

In this way, the controller can access Post and User model.


Create a model without using a database table

I need to create a model that does not use any table. For example, I want to use the $ validate array to verify the input data and ensure that the model logic is correct. However, when the table corresponding to the model is created does not exist, CakePHP reports an error. You can solve this problem by adding the following code to the model:

var $useTable = false;

You can also change the table name corresponding to the model in this way.

var $useTable = 'some_table';

Remember to exit () after redirection ()

For experienced people, this should be taken for granted. after calling $ this-> redirect (), the remaining code should exit () if you do not want to run it (). I also did this, but previously thought that $ this-> redirect () would call exit for me (not actually ).


Advanced model functions

By turning over the API, you can find a lot of useful functions that you don't know. I strongly recommend that you read the reference manual for the Model class at least once. The following are some important functions I have not noticed before:

??? GenerateList ()-mainly used to generate a selection box () Required data??? Query ()-Write an SQL statement by yourself to query??? FindCount ()-returns the number of rows that meet the specified conditions.??? HasAny ()-returns true if a record meets the conditionsI strongly recommend you read the reference of the entire model class again. you will be amazed at what you have learned.?How to insert multiple rows correctlyI need to traverse a list and insert each element into the database. I found that if the next insert is performed immediately after an insert is completed, the content inserted for the second time will not be inserted, but will be updated to the row inserted for the first time. For example:$ Items = array ('item 1', 'item 2', 'item 3'); foreach ($ items as $ Item) {$ this-> Post-> save (array ('post' => array ('title' => $ item )));}?This code inserts only one row in the posts table: "Item 3 ". CakePHP first inserts "Item 1", but immediately updates it to "Item 2" and then to "Item 3 ", because $ this-> Post-> id stores the id of the last successfully inserted row. This feature is usually useful, but it helps me in this example. In fact, you only need to set $ this-> Post-> id = false after each insert operation to solve this problem.Update: An email tells me that the correct method is to call create () to initialize the model and then set/save new data.?Insert logic before or after the controller functionSuppose you need to set a color array in each view rendered by the controller, but you do not want to define it in every action. You can use the beforeRender () callback function to implement:Function beforeRender () {$ this-> set ('Colors ', array ('red', 'Blue', 'green ');}?In this way, all views rendered by the controller can access the $ colors variable. The beforeRender () function is executed after the controller logic ends and the view is rendered. Similarly, beforeFilter () and afterFilter () functions are executed before and after each controller action. For more information, see models.?Add WYSIWYG editor for CakePHPHere is an excellent tutorial on how to use TinyMCE in CakePHP. Basically, you only need to link the tiny_mce.js file on the page, and then add some initialization code to set which textarea to change to the TinyMCE editor.?SQL statement for customizing the HABTM relationshipI tried to define a HABTM relation (has-and-belongs-to-lease) in a custom SQL statement, but encountered a problem. According to the document written in this article, you should first set finderSql in your model, but from the source code of CakePHP, you should set finderQuery. This is only a small problem in the document, but pointing out the problem can save time for others. Trac ticket is here.?Send emailI found two tutorials in wiki: sending emails and sending emails through PHPMailer. It is strongly recommended that the latter use PHPMailer to send emails more securely, and you do not need to process the mail headers by yourself, reducing a lot of trouble.?Custom HTML generated by HelperI need to modifyTo generate the "select" option to replace the default blank option. I also want the radio button to be labeled, so that you do not need to click the radio button accurately, but only need to click on the associated text.Create/app/config/tags. ini. php and add the following content:; Tag template for a input type = 'radio' tag. radio ="% S"; Tag template for an empty select option tag. selectempty ="-- Please Select --"?

You can obtain the complete tag list from/cake/config/tags. ini. php. However, I do not recommend modifying this file. Otherwise, your modifications may be lost when you upgrade CakePHP.

Custom 404 page

To customize the 404 page, create/app/views/errors/error404.thtml.







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.