Home > Article > Backend Development > 21 Tips CakePHP Programmers Must Know_PHP Tutorial
This article can be said to be the most classic among CakePHP tutorials. Although it is not a complete step-by-step series, the author summarized his own experience in using CakePHP in 21 items, which are very useful especially for novices.
During the translation, some words unique to CakePHP were intentionally left untranslated, such as controller, model, etc. I believe that people who have studied CakePHP should be able to understand their meaning immediately.
In addition, CakePHP’s wiki has expired and has been replaced by a website called bakery. The links to the wiki cited in the original article have also been updated to the bakery.
Quickly create static pages
I want to create several pages that only contain static data, use the default layout, and do not require any models. Initially I tried to create a controller and define an action for each static page. But this method is clumsy and not suitable for quickly creating static pages.
In fact, you can do it by using the pages controller - just create a view under the views/pages folder and access it through /pages. For example, I created /views/pages/matt.thtml, which can be accessed via http://www.example.com/pages/matt.
Change the title of the static page
If you want to change the page title when using pages controller, just 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 the layout (such as a variable indicating 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 background management program and want all management actions to be located in a specific folder, then open config/core.php and uncomment the following line:
define(CAKE_ADMIN, admin);
In this way, all actions starting with "admin_" can be accessed through /admin/yourcontroller/youraction. For example, if you create an action named "admin_add" in the 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 prevent others from accessing it at will.
View the SQL statements executed in the background
Just change the DEBUG constant in config/core.php to see the SQL statements executed in the background. 0 is product level, 1 is development level, 2 is complete debugging SQL, and 3 is complete debugging SQL and displaying 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 will break the page layout (especially when using Ajax to get the page and display it in the middle of the page instead of the bottom), you can add the following code in CSS to hide the debugging information:
#cakeSqlLog { display: none; }
This way you can maintain the page layout and see the debugging information by viewing the source code. Of course, don’t forget to change the debugging level back to 0 when you finally publish the website.
Get rich development documentation
Don’t always look at the manual. The wiki and API are also invaluable. The development guide in the wiki is very useful, and the API documentation seems difficult at first, 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. During the initial stages of development, I highly recommend using scaffolding to get your prototype program running. But if you clearly know that scaffolding is not suitable, I recommend you to use bake. bake will generate all files and save them to disk so that you can modify them at will. This saves the repetitive work of creating associations, views, and basic CRUD scrollder operations.
(Translator's Note: CRUD - Create, Read, Update, Delete, the four basic operations of database applications, namely "add, delete, check and modify".)
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 models, controllers and views in several steps. After creation, I usually read all the generated code and make any necessary changes.
Pay attention to permissions when publishing programs
Once when I was publishing a program, I packaged the entire cake directory and uploaded it to the server using scp. As soon as debugging information is turned off, an error occurs - the database call cannot return any data. I'm at a loss as I have to go through the debug information to debug the problem. Someone later told me that /app/tmp should be writable by apache. After changing the permissions to 777, the problem was solved.
Complex model verification
I need to perform more complex verification, not just simple verification that the input box is not empty or matches a certain regular expression. For example, I want to verify that the email address a user signed up with is already in use. I found this article about advanced verification in the wiki, which mentioned some very useful advanced verification methods.
Record error log
$this->log(Something broke);
This will log the error to /tmp/logs/ (I initially thought it would be logged to apache’s error log).
Let the controller use other models
If your controller needs to call data from different models, just use the following code at the beginning of the controller:
class yourController extends AppController {
var $uses = array(Post,User);
}
In this way, the controller can access the Post and User models.
Create a model that does not use database tables
I need to create a model that does not use any tables. For example, I want to easily verify the input data through the $validate array and maintain the correctness of the model logic. But when the model is created, the corresponding table does not exist, and CakePHP will report an error. This problem can be solved by adding the following code to the model:
var $useTable = false;
You can also change the table name corresponding to the model through this method.
var $useTable = some_table;
Remember to exit() after redirection
This should be a matter of course for experienced people. After calling $this->redirect(), the remaining code must exit() if you don’t want to run. I do this too, but previously thought $this->redirect() would call exit for me (it doesn't).
Advanced model functions
Looking through the API you can find many very useful functions that you don’t know about. I highly recommend reading the Model class reference manual at least once. Here are a few important functions that I didn’t notice before:
* generateList() - Mainly used to generate the data required for the selection box () * query() - Write your own SQL statement to query * findCount() - Return the number of rows that meet the specified conditions * hasAny() - When there is Returns true when the record meets the condition. Again, I strongly recommend reading the entire model class reference, you will be amazed at what you learn. How to insert multiple rows correctly I need to iterate through a list and insert each element in it into the database. I found that if I perform the next insert immediately after one insert is completed, the contents of the second insert will not be inserted at all, but will be updated to the first inserted row. For example: $items = array(Item 1,Item 2,Item 3); foreach ($items as $item) { $this->Post->save(array(Post => array(title => $ item))); } This code will insert only one row in the posts table: "Item 3". CakePHP first inserts "Item 1", but immediately updates it to "Item 2", and then updates it to "Item 3", because $this->Post->id saves the id of the row that was successfully inserted last time. Usually this feature is useful, but in this case it doesn't help. In fact, this problem can be solved by setting $this->Post->id = false after each insertion. Update: Someone sent me an email and told me that the correct way is to call create() to initialize the model, and then set/save the new data. Insert logic before or after the controller function Suppose you need to set a color array in every view rendered by the controller, but you don't want to define it in every action. This can be achieved through the beforeRender () callback function: function beforeRender () { $this->set(colors,array(red,blue,green); } } In this way, all views rendered by the controller can access the $colors variable. beforeRender ( ) function is executed after the controller logic is completed and before the view is rendered. Similarly, the beforeFilter() and afterFilter() functions are executed before and after each controller action. For more information, please read the models section of the manual. WYSIWYG Editor Here is a great tutorial on how to use TinyMCE with CakePHP. Basically you just link the tiny_mce.js file on the page and add some initialization code to set which textarea becomes the TinyMCE editor. That’s it. Customized HABTM relationship SQL statements I tried to define a HABTM relationship (has-and-belongs-to-many) on a custom SQL statement, but encountered a problem. According to the documentation at the time of writing this article, it should be. Set up finderSql in your own model first, but judging from the source code of CakePHP, you should set up finderQuery. This is just a small problem in the documentation, but pointing it out will save others time. Send me a Trac ticket here. I found two tutorials in the wiki: sending emails and sending emails through PHPMailer. The latter is highly recommended. Sending emails through PHPMailer is more secure, and you don’t need to deal with the email headers yourself, which reduces a lot of trouble. Customize the HTML generated by Helper. I need to modify the call $. html->selectTag() so that it generates the "please select" option instead of the default blank option. I also want the radio buttons to be labeled so the user doesn't have to click on the radio button itself exactly. Simply click on the associated text to create /app/config/tags.ini.php and add the following: Tag template for a input type=radio tag. radio = "%s"
; Tag template for an empty select option tag.
selectempty = "-- Please Select --"
You can get the complete list of tags from /cake/config/tags.ini.php. But I don't recommend modifying this file, otherwise your modifications may be lost when upgrading CakePHP.
Customized 404 page
If you need to customize the 404 page, just create /app/views/errors/error404.thtml.