CakePHP 21 tips you must know

Source: Internet
Author: User
The CakePHP framework is one of the most classic MVC agile development frameworks in PHP. it is easy to get started and easy to use, making it the first choice for many beginners to get started with the PHP framework. This document is not a new tutorial for CakePHP, but a CakePHP programmer with a little experience. Most of the details are mentioned in the official CakePHP document. here is a brief summary of the tips.

The CakePHP framework is one of the most classic MVC agile development frameworks in PHP. it is easy to get started and easy to use, making it the first choice for many beginners to get started with the PHP framework. This document is not a new tutorial for CakePHP, but a CakePHP programmer with a little experience. Most of the details are mentioned in the official CakePHP document. here is a brief summary of the tips.

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 practice, 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 the view file:

01 $ This-> 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:

01 $ This-> _ 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:

01 Define ('Cake _ admin', 'admin ');

All actions starting with "admin _" can be accessed through/admin/yourcontroller/youraction. For example, if an action named "admin_add" 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:

01 # 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. Bakera and APIs 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

One time 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
01 $ 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:

010203 ClassyourControllerextendsAppController {$ 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:

01 Var $ useTable = false;

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

01 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 the data query () required by the selection box-write an SQL statement by yourself to query findCount ()-return the number of rows meeting the specified conditions hasAny () -returns true if a record meets the conditions.

I 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 correctly

I 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:

01020304 $ Items = array ('item 1', 'item 2', 'item 3'); foreach ($ itemsas $ 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 function

Suppose 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:

010203 FunctionbeforeRender () {$ 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 CakePHP

Here 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 relationship

I 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 email

I 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 Helper

I need to modify

Create/app/config/tags. ini. php and add the following content:

01020304 Tag templatefora input type = 'radio' tag. radio ="% S"Tag templateforanemptyselect 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.

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.