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://m.miracleart.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);' //提交前驗證 ) ); 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,//所有選項 'multiple'=>'checkbox', 'selected' => $pushtypes,//選中的項 )); ?> </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://m.miracleart.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 訪問這個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,這樣每頁的底部會顯示出一個包含SQL調(diào)試信息的表格。
如果頁面底部添加的表格會破壞頁面布局(特別是使用Ajax獲取頁面并顯示到頁面中間而不是底部時),你可以在CSS中添加以下代碼以隱藏調(diào)試信息:
#cakeSqlLog { display: none; }
這樣既能保持頁面布局,又可以通過查看源代碼來看到調(diào)試信息。當(dāng)然最后發(fā)布網(wǎng)站時別忘了將調(diào)試級別改回0。
獲取豐富的開發(fā)文檔
別總是盯著手冊。wiki和API也是無價之寶。wiki中的開發(fā)指南十分有用,而API文檔初看起來比較難,但你很快就會發(fā)現(xiàn)這里的信息對你創(chuàng)建CakePHP網(wǎng)站十分重要。
使用bake.php
Bake是個命令行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ù)庫中建立一個表,然后到 /cake/scripts/ 目錄下執(zhí)行php bake.php 即可。
如果你通過交互方式來運(yùn)行bake,它會分幾步提示你創(chuàng)建model、controller和view。創(chuàng)建結(jié)束之后,我通常會閱讀所有生成的代碼并做必要的修改。
發(fā)布程序時注意權(quán)限
有一次我在發(fā)布程序時,將整個cake目錄打包然后用scp上傳到了服務(wù)器上。只要一關(guān)閉調(diào)試信息,就會出現(xiàn)錯誤——數(shù)據(jù)庫調(diào)用無法返回任何數(shù)據(jù)。我一籌莫展,因為我必須通過調(diào)試信息才能調(diào)試問題。后來有人告訴我,/app/tmp應(yīng)當(dāng)對apache可寫。將權(quán)限改為777之后問題就解決了。
復(fù)雜model驗證
我需要進(jìn)行更復(fù)雜的驗證,而不僅僅是驗證輸入框非空或者符合某個正則表達(dá)式這樣的簡單驗證。例如,我要驗證用戶注冊時使用的郵件地址是否已被使用。在wiki中我找到了這篇關(guān)于高級驗證的文章,其中提到了一些十分有用的高級驗證方法。
記錄錯誤日志
$this->log('Something broke');
這樣可以將錯誤記錄到 /tmp/logs/ 中(我最初以為會記錄到apache的錯誤日志中)。
讓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)建一個不使用任何表的model。例如,我想通過$validate數(shù)組方便底驗證輸入數(shù)據(jù),保持model邏輯的正確性。但創(chuàng)建model時對應(yīng)的表不存在,CakePHP就會報錯。通過在model中加入以下代碼可以解決這個問題:
var $useTable = false;
你也可以通過這種方法改變model對應(yīng)的表名。
var $useTable = 'some_table';
重定向之后記得exit()
對于有經(jīng)驗的人來說這應(yīng)當(dāng)是理所當(dāng)然的事兒,調(diào)用 $this->redirect() 之后,剩下的代碼如果不想運(yùn)行要exit()。我也這樣做,但以前曾經(jīng)認(rèn)為 $this->redirect() 會為我調(diào)用exit(實際上不會)。
高級model函數(shù)
翻翻API就能發(fā)現(xiàn)很多你不知道的非常有用的函數(shù)。我強(qiáng)烈推薦至少閱讀一遍 Model 類的參考手冊。下面是以前我沒注意到的幾個重要函數(shù):
① generateList()
- 主要用于生成選擇框(
再次強(qiáng)烈推薦閱讀整個model類參考,你會為你學(xué)到的東西贊嘆的。
如何正確插入多行
我需要遍歷一個列表,并將其中的每個元素都插入到數(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”,因為$this->Post->id保存的是上一次插入成功的行的id。通常這個特性很有用,但在這個例子中反而幫了倒忙。其實只要在每次插入之后設(shè)置 $this->Post->id = false 就可以解決這個問題。
更新:有人發(fā)郵件告訴我,正確的做法是調(diào)用create()初始化model,再set/save新數(shù)據(jù)。
在controller函數(shù)之前或之后插入邏輯
假設(shè)你需要在controller渲染的每個view中都設(shè)置一個顏色數(shù)組,但你不希望在每個action中都定義它??梢酝ㄟ^ beforeRender() 回調(diào)函數(shù)來實現(xiàn):
function beforeRender() { $this->set('colors',array('red','blue','green'); }
這樣該controller渲染的所有view都可以訪問$colors變量。beforeRender()函數(shù)在controller邏輯結(jié)束后、view被渲染之前執(zhí)行。同樣,beforeFilter()和afterFilter()函數(shù)會在每個controller action執(zhí)行的前后執(zhí)行。更多信息請閱讀手冊的models一節(jié)。
為CakePHP添加所見即所得編輯器
這里有一篇非常好的教程教你如何在CakePHP中使用TinyMCE?;旧夏阒恍柙陧撁嫔湘溄觮iny_mce.js文件,然后添加一些初始化代碼以設(shè)置將哪個textarea變成TinyMCE編輯器即可。
自定義HABTM關(guān)系的SQL語句
我曾試圖在自定義的SQL語句上定義一個HABTM關(guān)系(has-and-belongs-to-many),卻遇到了問題。根據(jù)本文撰稿時的文檔,應(yīng)當(dāng)先在自己的model中設(shè)置finderSql,但從CakePHP的源代碼來看,應(yīng)該設(shè)置finderQuery。這只是文檔中的一個小問題,但指出問題卻能為他人節(jié)約時間。Trac ticket在這里。
發(fā)送郵件
我在wiki中找到兩篇教程:發(fā)送郵件和通過PHPMailer發(fā)送郵件。強(qiáng)烈推薦后者,通過PHPMailer發(fā)送郵件更安全,而且不需要自己處理郵件頭,減少許多麻煩。
自定義Helper生成的HTML
我需要修改調(diào)用$html->selectTag()時生成的
建立 /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時可能會讓你的修改丟失。
自定義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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
