The examples in this article summarize common knowledge points of cakephp. Share it with everyone for your reference, the details are as follows:
1. Call the template of other controllers and redirect
Method 1:
Call the hello.ctp template under /views/tasks/tasks here
$this -> viewPath = 'tasks'; $this -> render('hello');
Method 2 (with parameters):
$this ->redirect(array('controller'=>'users','action'=>'welcome',urlencode($this->data['name'].'haha')));
2. Query
directly using sql:
$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 one can It is 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 no public style is required
$this->layout = false;
No need to render any view
$this->autoRender = false;
4. Define public methods/classes
Method 1:
You can define public methods 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 message
$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
Please refer to: http://ipnx.cn/
check(string $name);
Check whether there is a data item with $name as the key value in the Session.
del(string $name);<br/>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) ;
Return $name variable value.
renew
By creating a new seesion ID, deleting the original ID, and updating the information in the original Session to the new Session.
write(string $name, mixed $value);
Write the variables $name, $value into the session.
error
Returns the most recent error generated by Cake Session Component, often used for debugging.
7. Form
<?php echo $this->Form->create('Subject',array( 'type' => 'post', 'inputDefaults'=>array( 'p'=>false, 'label'=>false ), 'url'=>array( 'controller'=>'subjects', 'action'=>'edit' ), 'onsubmit'=>'return validateCallback(this, dialogAjaxDone);' //提交前驗(yàn)證 ) ); 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">下拉單選(編輯頁面會自動判斷選中)</p> <p class="ce"> <?php echo $this->Form->input('type',array('type'=>'select' ,'class'=>'ipt','options' => array(0=>'文章',1=>'專題', 2=>'圖組')));?> </p> </li> <li> <p class="ti">多選</p> <p class="ce"> <?php echo $this->Form->input('pushtype', array('type'=>'select', 'options' => $pushtype,//所有選項(xiàng) 'multiple'=>'checkbox', 'selected' => $pushtypes,//選中的項(xiàng) )); ?> </p> </li> </ul> <p class="btns_3"> <button class="btn3" type="submit"><span>保存</span></button> <button class="btn3 btn3_1 close"><span>取消</span></button> </p> <?php echo $this->Form->end();?>
##8. Log$this->log();
Call directly in the controller:$this->log('Something brok2',LOG_DEBUG);or call in the view: The types of logs are roughly as follows:
$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 log configuration options 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
Attachment: 21 tips you must know about CakePHP
This article can be said to be a CakePHP tutorial The most classic among them. Although it is not a complete step-by-step series, the author summarized his 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 learned CakePHP should be able to understand their meaning immediately. In addition, CakePHP's wiki has expired and was 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 model. 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 - as long as you create a view under the views/pages folder, you can access it through /pages. For example, I created /views/pages/matt.thtml, which can be accessed through http://ipnx.cn/.Change the title of the static page
If you want to change the page title when using the pages controller, just 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, indicating which part of the navigation bar should be highlighted variable), you can add the following code to the view:<? $this->_viewVars['somedata'] = array('some','data'); ?>This array can be accessed through $somedata in the 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 remove the comment from the following line:define('CAKE_ADMIN', 'admin');
這樣所有以"admin_"開頭的action都可以通過 /admin/yourcontroller/youraction 來訪問。例如,如果在posts controller中創(chuàng)建了名為"admin_add"的action,那么可以通過 www.example.com/admin/posts/add 訪問這個(gè)action。這樣就可以方便地為admin目錄設(shè)置密碼以避免他人隨意訪問。
查看后臺執(zhí)行的SQL語句
只需改變config/core.php中的DEBUG常量,即可看到后臺執(zhí)行的SQL語句。0為產(chǎn)品級,1為開發(fā)級,2為完整調(diào)試SQL,3為完整調(diào)試SQL并顯示對象數(shù)據(jù)。我通常將DEBUG設(shè)置為2,這樣每頁的底部會顯示出一個(gè)包含SQL調(diào)試信息的表格。
如果頁面底部添加的表格會破壞頁面布局(特別是使用Ajax獲取頁面并顯示到頁面中間而不是底部時(shí)),你可以在CSS中添加以下代碼以隱藏調(diào)試信息:
#cakeSqlLog { display: none; }
這樣既能保持頁面布局,又可以通過查看源代碼來看到調(diào)試信息。當(dāng)然最后發(fā)布網(wǎng)站時(shí)別忘了將調(diào)試級別改回0。
獲取豐富的開發(fā)文檔
別總是盯著手冊。wiki和API也是無價(jià)之寶。wiki中的開發(fā)指南十分有用,而API文檔初看起來比較難,但你很快就會發(fā)現(xiàn)這里的信息對你創(chuàng)建CakePHP網(wǎng)站十分重要。
使用bake.php
Bake是個(gè)命令行PHP腳本,可以根據(jù)數(shù)據(jù)庫自動生成model、controller和view。在開發(fā)的最初階段,我強(qiáng)烈推薦使用scaffolding讓你的原型程序跑起來。但如果你清楚地知道scaffolding不合適,我推薦你使用bake。bake會生成所有的文件并保存到磁盤上,以便你隨意修改。這樣能節(jié)省創(chuàng)建關(guān)聯(lián)、view、基本的CRUD crollder操作的重復(fù)工作。
(譯者注:CRUD - Create, Read, Update, Delete,數(shù)據(jù)庫應(yīng)用的四種基本操作,即"增刪查改"。)
bake很方便。你只需在數(shù)據(jù)庫中建立一個(gè)表,然后到 /cake/scripts/ 目錄下執(zhí)行php bake.php 即可。
如果你通過交互方式來運(yùn)行bake,它會分幾步提示你創(chuàng)建model、controller和view。創(chuàng)建結(jié)束之后,我通常會閱讀所有生成的代碼并做必要的修改。
發(fā)布程序時(shí)注意權(quán)限
有一次我在發(fā)布程序時(shí),將整個(gè)cake目錄打包然后用scp上傳到了服務(wù)器上。只要一關(guān)閉調(diào)試信息,就會出現(xiàn)錯(cuò)誤——數(shù)據(jù)庫調(diào)用無法返回任何數(shù)據(jù)。我一籌莫展,因?yàn)槲冶仨毻ㄟ^調(diào)試信息才能調(diào)試問題。后來有人告訴我,/app/tmp應(yīng)當(dāng)對apache可寫。將權(quán)限改為777之后問題就解決了。
復(fù)雜model驗(yàn)證
我需要進(jìn)行更復(fù)雜的驗(yàn)證,而不僅僅是驗(yàn)證輸入框非空或者符合某個(gè)正則表達(dá)式這樣的簡單驗(yàn)證。例如,我要驗(yàn)證用戶注冊時(shí)使用的郵件地址是否已被使用。在wiki中我找到了這篇關(guān)于高級驗(yàn)證的文章,其中提到了一些十分有用的高級驗(yàn)證方法。
記錄錯(cuò)誤日志
$this->log('Something broke');
這樣可以將錯(cuò)誤記錄到 /tmp/logs/ 中(我最初以為會記錄到apache的錯(cuò)誤日志中)。
讓controller使用其他model
如果你的controller需要調(diào)用來自不同model的數(shù)據(jù),只要在controller開頭使用如下代碼:
class yourController extends AppController { var $uses = array('Post','User'); }
這樣controller就能訪問Post和User model了。
創(chuàng)建不使用數(shù)據(jù)庫表的model
我需要創(chuàng)建一個(gè)不使用任何表的model。例如,我想通過$validate數(shù)組方便底驗(yàn)證輸入數(shù)據(jù),保持model邏輯的正確性。但創(chuàng)建model時(shí)對應(yīng)的表不存在,CakePHP就會報(bào)錯(cuò)。通過在model中加入以下代碼可以解決這個(gè)問題:
var $useTable = false;
你也可以通過這種方法改變model對應(yīng)的表名。
var $useTable = 'some_table';
重定向之后記得exit()
對于有經(jīng)驗(yàn)的人來說這應(yīng)當(dāng)是理所當(dāng)然的事兒,調(diào)用 $this->redirect() 之后,剩下的代碼如果不想運(yùn)行要exit()。我也這樣做,但以前曾經(jīng)認(rèn)為 $this->redirect() 會為我調(diào)用exit(實(shí)際上不會)。
高級model函數(shù)
翻翻API就能發(fā)現(xiàn)很多你不知道的非常有用的函數(shù)。我強(qiáng)烈推薦至少閱讀一遍 Model 類的參考手冊。下面是以前我沒注意到的幾個(gè)重要函數(shù):
① generateList()
- 主要用于生成選擇框(
再次強(qiáng)烈推薦閱讀整個(gè)model類參考,你會為你學(xué)到的東西贊嘆的。
如何正確插入多行
我需要遍歷一個(gè)列表,并將其中的每個(gè)元素都插入到數(shù)據(jù)庫中。我發(fā)現(xiàn)如果在一次插入完成后立即進(jìn)行下一次插入,那么第二次插入的內(nèi)容完全不會被插入,而是會被更新到第一次插入的行中。例如:
$items = array('Item 1','Item 2','Item 3'); foreach ($items as $item) { $this->Post->save(array('Post' => array('title' => $item))); }
這段代碼將在posts表中插入僅一行:“Item 3”。CakePHP首先插入“Item 1”,但馬上將其更新為“Item 2”,再更新為“Item 3”,因?yàn)?this->Post->id保存的是上一次插入成功的行的id。通常這個(gè)特性很有用,但在這個(gè)例子中反而幫了倒忙。其實(shí)只要在每次插入之后設(shè)置 $this->Post->id = false 就可以解決這個(gè)問題。
更新:有人發(fā)郵件告訴我,正確的做法是調(diào)用create()初始化model,再set/save新數(shù)據(jù)。
在controller函數(shù)之前或之后插入邏輯
假設(shè)你需要在controller渲染的每個(gè)view中都設(shè)置一個(gè)顏色數(shù)組,但你不希望在每個(gè)action中都定義它。可以通過 beforeRender() 回調(diào)函數(shù)來實(shí)現(xiàn):
function beforeRender() { $this->set('colors',array('red','blue','green'); }
這樣該controller渲染的所有view都可以訪問$colors變量。beforeRender()函數(shù)在controller邏輯結(jié)束后、view被渲染之前執(zhí)行。同樣,beforeFilter()和afterFilter()函數(shù)會在每個(gè)controller action執(zhí)行的前后執(zhí)行。更多信息請閱讀手冊的models一節(jié)。
為CakePHP添加所見即所得編輯器
這里有一篇非常好的教程教你如何在CakePHP中使用TinyMCE。基本上你只需在頁面上鏈接tiny_mce.js文件,然后添加一些初始化代碼以設(shè)置將哪個(gè)textarea變成TinyMCE編輯器即可。
自定義HABTM關(guān)系的SQL語句
我曾試圖在自定義的SQL語句上定義一個(gè)HABTM關(guān)系(has-and-belongs-to-many),卻遇到了問題。根據(jù)本文撰稿時(shí)的文檔,應(yīng)當(dāng)先在自己的model中設(shè)置finderSql,但從CakePHP的源代碼來看,應(yīng)該設(shè)置finderQuery。這只是文檔中的一個(gè)小問題,但指出問題卻能為他人節(jié)約時(shí)間。Trac ticket在這里。
發(fā)送郵件
我在wiki中找到兩篇教程:發(fā)送郵件和通過PHPMailer發(fā)送郵件。強(qiáng)烈推薦后者,通過PHPMailer發(fā)送郵件更安全,而且不需要自己處理郵件頭,減少許多麻煩。
自定義Helper生成的HTML
我需要修改調(diào)用$html->selectTag()時(shí)生成的
建立 /app/config/tags.ini.php,然后添加以下的內(nèi)容:
; 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>"
你可以從/cake/config/tags.ini.php中獲得完整的標(biāo)簽列表。但我不建議修改該文件,否則升級CakePHP時(shí)可能會讓你的修改丟失。
自定義404頁面
如果你需要自定義404頁面,只需創(chuàng)建 /app/views/errors/error404.thtml。
更多cakephp知識點(diǎn)匯總相關(guān)文章請關(guān)注PHP中文網(wǎng)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
