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://www.php.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);
$levels = array( LOG_WARNING=> 'warning', LOG_NOTICE=> 'notice', LOG_INFO=> 'info', LOG_DEBUG=> 'debug', LOG_ERR=> 'error', LOG_ERROR=> 'error' );
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://www.php.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'); ?>
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中创建了名为"admin_add"的action,那么可以通过 www.example.com/admin/posts/add 访问这个action。这样就可以方便地为admin目录设置密码以避免他人随意访问。
查看后台执行的SQL语句
只需改变config/core.php中的DEBUG常量,即可看到后台执行的SQL语句。0为产品级,1为开发级,2为完整调试SQL,3为完整调试SQL并显示对象数据。我通常将DEBUG设置为2,这样每页的底部会显示出一个包含SQL调试信息的表格。
如果页面底部添加的表格会破坏页面布局(特别是使用Ajax获取页面并显示到页面中间而不是底部时),你可以在CSS中添加以下代码以隐藏调试信息:
#cakeSqlLog { display: none; }
这样既能保持页面布局,又可以通过查看源代码来看到调试信息。当然最后发布网站时别忘了将调试级别改回0。
获取丰富的开发文档
别总是盯着手册。wiki和API也是无价之宝。wiki中的开发指南十分有用,而API文档初看起来比较难,但你很快就会发现这里的信息对你创建CakePHP网站十分重要。
使用bake.php
Bake是个命令行PHP脚本,可以根据数据库自动生成model、controller和view。在开发的最初阶段,我强烈推荐使用scaffolding让你的原型程序跑起来。但如果你清楚地知道scaffolding不合适,我推荐你使用bake。bake会生成所有的文件并保存到磁盘上,以便你随意修改。这样能节省创建关联、view、基本的CRUD crollder操作的重复工作。
(译者注:CRUD - Create, Read, Update, Delete,数据库应用的四种基本操作,即"增删查改"。)
bake很方便。你只需在数据库中建立一个表,然后到 /cake/scripts/ 目录下执行php bake.php 即可。
如果你通过交互方式来运行bake,它会分几步提示你创建model、controller和view。创建结束之后,我通常会阅读所有生成的代码并做必要的修改。
发布程序时注意权限
有一次我在发布程序时,将整个cake目录打包然后用scp上传到了服务器上。只要一关闭调试信息,就会出现错误——数据库调用无法返回任何数据。我一筹莫展,因为我必须通过调试信息才能调试问题。后来有人告诉我,/app/tmp应当对apache可写。将权限改为777之后问题就解决了。
复杂model验证
我需要进行更复杂的验证,而不仅仅是验证输入框非空或者符合某个正则表达式这样的简单验证。例如,我要验证用户注册时使用的邮件地址是否已被使用。在wiki中我找到了这篇关于高级验证的文章,其中提到了一些十分有用的高级验证方法。
记录错误日志
$this->log('Something broke');
这样可以将错误记录到 /tmp/logs/ 中(我最初以为会记录到apache的错误日志中)。
让controller使用其他model
如果你的controller需要调用来自不同model的数据,只要在controller开头使用如下代码:
class yourController extends AppController { var $uses = array('Post','User'); }
这样controller就能访问Post和User model了。
创建不使用数据库表的model
我需要创建一个不使用任何表的model。例如,我想通过$validate数组方便底验证输入数据,保持model逻辑的正确性。但创建model时对应的表不存在,CakePHP就会报错。通过在model中加入以下代码可以解决这个问题:
var $useTable = false;
你也可以通过这种方法改变model对应的表名。
var $useTable = 'some_table';
重定向之后记得exit()
对于有经验的人来说这应当是理所当然的事儿,调用 $this->redirect() 之后,剩下的代码如果不想运行要exit()。我也这样做,但以前曾经认为 $this->redirect() 会为我调用exit(实际上不会)。
高级model函数
翻翻API就能发现很多你不知道的非常有用的函数。我强烈推荐至少阅读一遍 Model 类的参考手册。下面是以前我没注意到的几个重要函数:
① generateList()
- 主要用于生成选择框(
再次强烈推荐阅读整个model类参考,你会为你学到的东西赞叹的。
如何正确插入多行
我需要遍历一个列表,并将其中的每个元素都插入到数据库中。我发现如果在一次插入完成后立即进行下一次插入,那么第二次插入的内容完全不会被插入,而是会被更新到第一次插入的行中。例如:
$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。通常这个特性很有用,但在这个例子中反而帮了倒忙。其实只要在每次插入之后设置 $this->Post->id = false 就可以解决这个问题。
更新:有人发邮件告诉我,正确的做法是调用create()初始化model,再set/save新数据。
在controller函数之前或之后插入逻辑
假设你需要在controller渲染的每个view中都设置一个颜色数组,但你不希望在每个action中都定义它。可以通过 beforeRender() 回调函数来实现:
function beforeRender() { $this->set('colors',array('red','blue','green'); }
这样该controller渲染的所有view都可以访问$colors变量。beforeRender()函数在controller逻辑结束后、view被渲染之前执行。同样,beforeFilter()和afterFilter()函数会在每个controller action执行的前后执行。更多信息请阅读手册的models一节。
为CakePHP添加所见即所得编辑器
这里有一篇非常好的教程教你如何在CakePHP中使用TinyMCE。基本上你只需在页面上链接tiny_mce.js文件,然后添加一些初始化代码以设置将哪个textarea变成TinyMCE编辑器即可。
自定义HABTM关系的SQL语句
我曾试图在自定义的SQL语句上定义一个HABTM关系(has-and-belongs-to-many),却遇到了问题。根据本文撰稿时的文档,应当先在自己的model中设置finderSql,但从CakePHP的源代码来看,应该设置finderQuery。这只是文档中的一个小问题,但指出问题却能为他人节约时间。Trac ticket在这里。
发送邮件
我在wiki中找到两篇教程:发送邮件和通过PHPMailer发送邮件。强烈推荐后者,通过PHPMailer发送邮件更安全,而且不需要自己处理邮件头,减少许多麻烦。
自定义Helper生成的HTML
我需要修改调用$html->selectTag()时生成的
建立 /app/config/tags.ini.php,然后添加以下的内容:
; 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中获得完整的标签列表。但我不建议修改该文件,否则升级CakePHP时可能会让你的修改丢失。
自定义404页面
如果你需要自定义404页面,只需创建 /app/views/errors/error404.thtml。
更多cakephp知识点汇总相关文章请关注PHP中文网!