CakePHP Knowledge Points Summary

Source: Internet
Author: User
This paper summarizes the common knowledge points of cakephp. Share to everyone for your reference, as follows:

1. Invoke templates for other controllers, redirect

Method One:

Call the HELLO.CTP template under/views/tasks/tasks here

$this-ViewPath = ' tasks '; $this, render (' Hello ');

Method two (with reference):

$this->redirect (' controller ' = ' users ', ' action ' = ' welcome ', UrlEncode ($this->data[' name '). ' Haha '));

2. Enquiry

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 '),)  );

The parameter of find, the first can be all, a, count, the second parameter is an array, the key of the array can be: conditions, fields, order, limit, offset, joins.

Add to:

$this->clue->create (); $this->clue->save ($this->data);

Modify:

$this->clue->create (); $this->clue->save ($this->data);

Delete:

$this->clue->delete ($id)

3. When no public style is required

$this->layout = false;

Do not render any view

$this->autorender = false;

4. Define Public methods/classes

Method One:

Public methods can be defined in/app/controller/appcontroller.php

Call

$this->test ();

Method Two:

Create utillcomponent.php in/app/controllers/components

<?php  class Utillcomponent extends Object  {   function juanstr ($str) {     return $str. ' +juanstr ';   }  }?>

Call:

var $components = array (' Utill '), $digit 1 = $this->utill->juanstr ($digit 1);

5. Define the prompt information

$this->session->setflash (' The user has been saved '); <p class= "wrong" ><?php Echo $this->session- >flash ();? ></p>

Or

$this->session->write (' Message.auth ', Array (' Message ' =>__ (' The user has been saved. ', true), ' element ' = ' ', ' params ' =>array ()); <p class= "wrong" ><?php Echo $this->session->flash (' auth ');? ></p>

6. Session Settings

Refer to: http://www.php.cn/

check(string $name);

Check to see if there are data items in the session that have $name as key values.

del(string $name);
delete(string $name);

Deletes the Session variable specified by $name.

Valid returns True when the session is valid, preferably before the read () operation to determine whether the session you are trying to access is actually valid.

read(string $name);

Returns the value of the $name variable.

Renew

Update the information in the previous session to the new session by creating a new Seesion ID, deleting the original ID.

write(string $name, mixed $value);

$name the variable $value write to the session.

Error

Returns the most recent error generated by the Cake Session Component, often used for debugging.

7. Forms

<?php echo $this->form->create (' Subject ', Array (' type ' = ' + ' post ', ' Inputdefaults ' =>array (' P ' =>fals E, ' label ' =>false), ' url ' =>array (' controller ' = ' subjects ', ' action ' = ' edit '), ' Onsubmi T ' = = ' return Validatecallback (this, dialogajaxdone); '//Pre-submission verification); Echo $this->form->input (' id ', array (' type ' = > ' hidden '); Echo $this->form->input (' uid ', array (' type ' = ' hidden '));? ><ul class= "Usr_info_basic" ><li> <p class= "Ti" > Under Lathan (Edit page is automatically selected) </p> <p class= "CE" ><?php echo $this->form->input (' type ', array (' type ' = ' select ', ' class ' = ' IPT ', ' options ' = Array (0=> ' article ',1=> ' theme ', 2=> ' graph Group ')));? > </p></li><li> <p class= "Ti" > Multi-select </p> <p class= "Ce" ><?php echo $this->for M->input (' Pushtype ', Array (' type ' = ' = ' select ', ' options ' = = $pushtype,//All options ' multiple ' = ' checkbox ', ' s Elected ' = $pushtypes,//Selected items);? > </p></li></ul><p class= "Btns_3" > <button class= "btn3" type= "Submit" ><span> save </ span></button> <button class= "btn3 btn3_1 Close" ><span> Cancel </span></button></p ><?php echo $this->form->end ();? >

8. Log $this->log ();

Called directly in the controller:

$this->log (' Something brok2 ', log_debug);

or view call:

<?php $this->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 saved in the/app/tmp/logs directory.

There are configuration options for logs in the/app/config/core.php file:

Define (' Log_error ', 2);

9. Render Path

Echo APP. ' Webroot '. Ds;//d:\wamp\www\cakephp\app\webroot\echo app. ' Webroot ';D: \wamp\www\cakephp\app\webroot

Attached: 21 tips for cakephp to know

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.php.cn/.

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:

<? $this->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:

<? $this->_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() -The data needed to generate the selection box (<SELECT>) primarily
query() -Write your own SQL statement to query
findCount() -Returns the number of rows that meet the specified criteria
hasAny() -Returns True when a record satisfies a condition

It is highly recommended to read the entire model reference, and you will be amazed at what you learn.

How to insert multiple lines 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 (' t Itle ' = $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

Suppose you need to set a color array in each view that the controller renders, but you don't want to define it in each action. The BeforeRender () callback function can be used to implement:

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 are executed before and after each controller action. For more information, please read the models section of the manual.

Add WYSIWYG editor to 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 statements for customizing HABTM relationships

I tried to define a HABTM relationship (Has-and-belongs-to-many) on a custom SQL statement, but I encountered 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 mail and sending mail through 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 <OPTION> generated when calling $html->selecttag (), so that it generates the "select" option instead of the default white space 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.

Build the/app/config/tags.ini.php, and then add the following content:

; Tag template for a input type= ' radio ' Tag.radio = "<input type=" Radio "name=" data[%s][%s] "id="%s "%s/><label fo R= "%3$s" >%s</label> "; Tag template for a empty select option Tag.selectempty = "<option value=" "%s>--Please select--</option>"

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.

Related Article

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.