21 tips for CakePHP programmers

Source: Internet
Author: User

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 http://www.example.com/pages/matt.

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 "admin_add" is created in posts controller, you can access this action through www.example.com/admin/posts/add. 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 the data required by the Selection box () * query ()-write an SQL statement by yourself to query * findCount ()-return the number of rows meeting the specified conditions * hasAny () -If a record meets the condition, the returned result is true. We strongly recommend that you read the reference of the entire model class. You will be amazed at what you have learned. 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. 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 the logic before or after the controller function. Assume that 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. The beforeRender () callback function can be used 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 wysiwysiwyg 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. I tried to define an has-and-belongs-to-sequence on 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. I found two tutorials on sending emails 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. Customize the HTML generated by Helper. I need to modify the html generated when calling $ HTML-> selectTag () to generate the "select" option instead of 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: info-contact@alibabacloud.com 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.