21 tips that cakephp programmers must know

Source: Internet
Author: User
Tags php script

This article can be said to be the most classic of the cakephp tutorial. While not a complete hands-on series, the authors summarize 21 of their own experience with cakephp, which is especially useful for beginners. In translation, deliberately retained some of CakePHP's unique words are not translated, such as controller, model and so on. Believe that someone who has learned cakephp should be a horse.

This article can be said to be the most classic of the cakephp tutorial. While not a complete hands-on series, the authors summarize 21 of their own experience with cakephp, which is especially useful for beginners.

In translation, deliberately retained some of CakePHP's unique words are not translated, such as controller, model and so on. Believe that people who have learned cakephp should be able to understand what they mean right away.

In addition, CakePHP's wiki has been invalidated and replaced by a website called Bakery. Links to the wiki referenced in the original text have also been updated to bakery.

Quickly create a static page

I want to create several pages that contain only static data, use the default layout, and do not need any model. Initially I tried to create a controller and define an action for each static page. But this approach is clumsy and not suitable for creating static pages quickly.

In fact, you can do this by using the pages controller-as long as you create a view under the Views/pages folder, you can access it through/pages. For example, I created the/views/pages/matt.thtml and I can access it through Http://www.example.com/pages/matt.

Change the title of a static page

If you want to change the page title when using the pages controller, simply add the following code to the view:

PageTitle = "Title of your page."; ?>

Send data to layout in a static page

If you need to pass data to layout (for example, a variable that indicates which part of the navigation bar should be highlighted), you can add the following code to the view:

_viewvars[' somedata ' = Array (' Some ', ' data ');?>

This array can be accessed through $somedata in layout.

Quickly create background management

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

Define (' Cake_admin ', ' ADMIN ');

All actions that begin with "Admin_" can then be accessed through/admin/yourcontroller/youraction. For example, if you create an action named "Admin_add" in the posts controller, you can access the action by Www.example.com/admin/posts/add. This makes it easy to set a password for the admin directory to avoid random access by others.

View SQL statements executed in the background

Simply change the debug constants in the config/core.php to see the SQL statements executed in the background. 0 for product level, 1 for development level, 2 for full debug sql,3 for full debug SQL and display object data. I usually set debug to 2 so that a table with SQL debugging information appears at the bottom of each page.

If the table added at the bottom of the page breaks the page layout (especially if you use Ajax to get the page and display it in the middle of the page instead of the bottom), you can add the following code to the CSS to hide the debug information:

#cakeSqlLog {display:none;}

This allows you to maintain the layout of the page and see the debug information by looking at the source code. Of course, when you finally publish the site, don't forget to change the debug level back to 0.

Get Rich development documentation

Don't always stare at the manual. Wikis and APIs are priceless. The development guide in the wiki is useful, and the API documentation looks difficult at first, but you'll soon find that the information here is important for you to create a cakephp site. `

Using bake.php

Bake is a command-line PHP script that automatically generates model, controller, and view based on the database. In the early stages of development, I strongly recommend using scaffolding to get your prototype running. But if you know clearly that scaffolding is inappropriate, I recommend you to use bake. Bake will generate all of the files and save them to disk so that you can modify them arbitrarily. This saves duplication of effort to create associated, view, basic crud crollder operations.

(Translator Note: Crud-create, Read, Update, Delete, database application of four basic operations, that is, "adding and deleting changes." )

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

If you run bake interactively, it will prompt you to create model, controller, and view in a few steps. After the creation is finished, I usually read all the generated code and make the necessary changes.

Note Permissions when you publish a program

One time when I was publishing a program, I packaged the entire cake directory and then uploaded it to the server using SCP. As soon as the debug information is turned off, an error occurs--the database call cannot return any data. I helpless because I had to debug the problem by debugging the information. Later someone told me that/app/tmp should be written to Apache. The problem is resolved after you change the permissions to 777.

Complex model validation

I need more complex validation than just validating that the input box is not empty or conforms to a simple validation of a regular expression. For example, I want to verify that the email address used by the user registration is already in use. In the wiki I found this article on advanced validation, which mentions some of the most useful advanced authentication methods.

Logging error logs

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

This makes it possible to log errors to/tmp/logs/(which I initially thought would be recorded in Apache's error log).

Let controller use other model

If your controller needs to invoke data from a different model, simply use the following code at the beginning of the controller:

Class Yourcontroller extends AppController {

var $uses = array (' Post ', ' User ');

}

This allows the controller to access the post and user model.

To create a model that does not use a database table

I need to create a model that doesn't use any tables. For example, I want to validate the input data with the $validate array, and keep the model logic correct. However, the corresponding table when creating the model does not exist, CakePHP will error. This problem can be solved by adding the following code to the model:

var $useTable = false;

You can also use this method to change the name of the model corresponding to the table.

var $useTable = ' some_table ';

After redirection remember exit ()

For experienced people this should be a matter of course, after the call $this->redirect (), the remaining code if you do not want to run to exit (). I did the same, but I used to think that $this->redirect () would call Exit for me (not really).

Advanced model functions

Flipping through the API will reveal a lot of useful functions that you don't know about. I strongly recommend reading the reference manual of the Model class at least once. Here are a few important functions that I haven't noticed before:

  * Generatelist ()-primarily used to generate the selection box () required data * query ()-Write your own SQL statement to query * FINDCOUNT ()-Returns the number of rows that meet the specified criteria * Hasany ()-Returns true once the condition has been met  It is highly recommended to read the entire model reference and you will be amazed at what you have learned. How to insert multiple rows correctly I need to iterate through a list and insert each of these elements into the database. I found that if the next insertion occurs immediately after the insertion is complete, the second insert is not inserted at all, but is updated to the first inserted row.   For example: $items = Array (' Item 1 ', ' Item 2 ', ' Item 3 ');   foreach ($items as $item) {$this->post->save (' Post ' + = ' Array (' title ' = = $item)); This code will insert only one line in the posts table: "Item 3". CakePHP First Inserts "Item 1", but immediately updates it to "Item 2" and then updates to "Item 3" because $this->post->id saves the ID of the last row that was inserted successfully. This feature is often useful, but in this case it helps.  In fact, you can solve this problem by setting $this->post->id = False after each insert.  Update: Someone sent me an email telling me that the right thing to do is to call Create () to initialize the model and then set/save the new data. Inserting logic before or after the controller function assumes that you need to set a color array in each view that the controller renders, but you do not want to define it in each action.   Can be implemented through the BeforeRender () callback function: function BeforeRender () {$this->set (' Colors ', array (' Red ', ' blue ', ' green '); This allows all view rendered by the controller to access the $colors variable. The BeforeRender () function executes after the controller logic finishes and before the view is rendered. Similarly, the Beforefilter () and Afterfilter () functions will be in each ControlleThe R action executes before and after execution.  For more information, please read the models section of the manual. Add WYSIWYG editor for cakephp here's a great tutorial on how to use TINYMCE in cakephp.  Basically you simply link the tiny_mce.js file on the page, and then add some initialization code to set which textarea will become the TINYMCE editor. SQL statement for customizing HABTM relationships I tried to define a HABTM relationship (Has-and-belongs-to-many) on a custom SQL statement, but I ran into a problem. According to the documentation at the time of writing, you should set the Findersql in your model, but from CakePHP's source code, you should set the Finderquery. This is only a small issue in the documentation, but pointing out the problem can save time for others.  Trac ticket is here. Send mail I found two tutorials in the wiki: sending messages and sending them via Phpmailer.  It is highly recommended that the latter be more secure to send mail via Phpmailer, and do not need to handle mail headers yourself, reducing a lot of hassle. Customizing helper-generated HTML I need to modify the generated when calling $html->selecttag () to generate a "select" option instead of the default blank option.  I also want the radio button to be labeled so that the user doesn't have to click on the radio button itself, but just click on the associated text. Set up/app/config/tags.ini.php, and then 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 get a complete list of tags from/cake/config/tags.ini.php. However, I do not recommend that you modify the file, or you may lose your modifications if you upgrade cakephp.

customizing 404 pages

If you need to customize the 404 page, just create a/app/views/errors/error404.thtml.

21 tips that cakephp programmers must know

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.