This article mainly introduces common knowledge points of cakephp, summarizes and sorts out the template, database, log, form and other related operation skills of cakephp. if you need them, refer to the examples in this article to summarize the common knowledge points of cakephp. We will share this with you for your reference. The details are as follows:
1. call templates of other controllers to redirect
Method 1:
Call the hello. ctp template under/views/tasks
$this -> viewPath = 'tasks';$this -> render('hello');
Method 2 (with parameters ):
$ This-> redirect (array ('controller' => 'users', 'Action' => 'Welcome ', urlencode ($ this-> data ['name']. 'hahaha ')));
2. query
Use SQL directly:
$this->PostContent->query("select * from user");find():$clue = $this->clue->find('all', array( 'fields' =>array( 'id', 'title', 'content' ), 'order' => 'id ASC', 'conditions' => array('id' => '1'), ));
Find parameters. The first parameter can be all, first, and count. The second parameter is an array. the key of the array can be conditions, fields, order, limit, offset, and joins.
Add:
$this->clue->create();$this->clue->save($this->data);
Modify:
$this->clue->create();$this->clue->save($this->data);
Delete:
$this->clue->delete($id)
3. when public styles are not required
$this->layout = false;
No view rendering required
$this->autoRender = false;
4. define public methods/classes
Method 1:
Public methods can be defined in/app/Controller/AppController. php.
Call
$this->test();
Method 2:
Create UtillComponent. php in/app/controllers/components
Call:
var $components = array('Utill');$digit1 = $this->Utill->juanstr($digit1);
5. define prompt information
$this->Session->setFlash(__('The user has been saved'));
Session->flash();?>
Or
$this->Session->write('Message.auth',array('message'=>__('The user has been saved.',true),'element'=>'','params'=>array()));
Session->flash('auth');?>
6. session settings
Refer :#
check(string $name);
Check whether $ name is a key value in the Session.
del(string $name);
delete(string $name);
Delete the Session variable specified by $ name.
Valid returns true when the Session is valid. it is best to use it before the read () operation to determine whether the Session you want to access is indeed valid.
read(string $name);
Returns the value of $ name.
Renew
Create a new seesion ID, delete the original ID, and update the information in the original Session to the new Session.
write(string $name, mixed $value);
Write the variable $ name and $ value to the session.
Error
Returns an error recently generated by the Cake Session Component, which is often used for debugging.
7. form
Form-> create ('subobject', array ('type' => 'post', 'inputdefaults' => array ('P' => false, 'label' => false), 'URL' => array ('controller' => 'objects', 'Action' => 'Edit '), 'onsubmit '=> 'Return validateCallback (this, dialogAjaxDone);' // pre-submission verification); echo $ this-> Form-> input ('id ', array ('type' => 'did'); echo $ this-> Form-> input ('uid ', array ('type' => 'ddn');?>
-
Select one option from the drop-down list (the editing page automatically determines the selected option)
Form-> input ('type', array ('type' => 'select', 'class' => 'ipt ', 'options' => array (0 => 'topic ', 1 => 'topic', 2 => 'graph group');?>
-
Multiple choice
Form-> input ('pushtype', array ('type' => 'select', 'options' => $ pushtype, // All options 'multiple '=> 'checkbox', 'selected' => $ pushtypes, // selected items);?>
Save Cancel
Form-> end ();?>
8. log $ this-> log ();
Directly call in controller:
$this->log('Something brok2',LOG_DEBUG);
Or call in view:
log('Something brok2',LOG_DEBUG); ?>
There are roughly the following types of logs:
$levels = array( LOG_WARNING=> 'warning', LOG_NOTICE=> 'notice', LOG_INFO=> 'info', LOG_DEBUG=> 'debug', LOG_ERR=> 'error', LOG_ERROR=> 'error');
Log files are stored in the/app/tmp/logs directory.
Log configuration options are available in the/app/config/core. php file:
define('LOG_ERROR', 2);
9. rendering path
echo APP . 'webroot' . DS;//D:\wamp\www\cakephp\app\webroot\echo APP . 'webroot' ;D:\wamp\www\cakephp\app\webroot
Appendix: 21 tips required by CakePHP
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, if I have created/views/pages/matt. thtml, I can access it through.
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 are added, deleted, queried, modified, and deleted ".)
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()
-Used to generate a selection box () Required data②Query ()-Write SQL statements by yourself to query③FindCount ()-Returns the number of rows meeting the specified condition.④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 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.
For more information about cakephp, see The PHP Chinese website!