Summary of common knowledge points of cakephp and cakephp

Source: Internet
Author: User

Summary of common knowledge points of cakephp and cakephp

This example summarizes 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

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

Call:

var $components = array('Utill');$digit1 = $this->Utill->juanstr($digit1);

5. Define 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

See: http://www.bkjia.com/article/106557.htm

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

<? Php echo $ this-> Form-> create ('subobject', array ('type' => 'post', 'inputdefaults' => array ('div '=> 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');?> <Ul class = "usr_info_basic"> <li> <div class = "ti"> drop-down mode (the selected option is automatically determined on the editing page) </div> <div class = "ce"> <? Php echo $ this-> Form-> input ('type', array ('type' => 'select', 'class' => 'ipt ', 'options' => array (0 => 'topic ', 1 => 'topic', 2 => 'graph group');?> </Div> </li> <div class = "ti"> multiple choice </div> <div class = "ce"> <? Php echo $ this-> Form-> input ('pushtype', array ('type' => 'select', 'options' => $ pushtype, // all options 'Multiple '=> 'checkbox', 'selected' => $ pushtypes, // selected items);?> </Div> </li> </ul> <div class = "btns_3"> <button class = "btn3" type = "submit"> <span> Save </span> </button> <button class = "btn3 btn3_1 close"> <span> cancel </span> </button> </div> <? Php echo $ this-> Form-> end ();?>

8. log $ this-> log ();

Directly call in controller:

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

Or call in view:

<?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 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, 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:

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

<? $this->_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()-Mainly used to generate the data required by the Selection box (<SELECT>)
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 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. 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 function

Suppose 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 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.

SQL statement for customizing the HABTM relationship

I 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 email

I 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 Helper

I need to modify the <option> generated when I call $ html-> selectTag () to 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 = "<input type="radio" name="data[%s][%s]" id="%s" %s /><label for="%3$s">%s</label>"; Tag template for an empty select option tag.selectempty = "<option value="" %s>-- Please Select --</option>"

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.