Home > Backend Development > PHP Tutorial > Summary of cakephp knowledge points

Summary of cakephp knowledge points

高洛峰
Release: 2023-03-06 07:04:01
Original
1276 people have browsed it

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');
Copy after login

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

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);
Copy after login
Copy after login

Modify:

$this->clue->create();
$this->clue->save($this->data);
Copy after login
Copy after login

Delete:

$this->clue->delete($id)
Copy after login

3. When no public style is required

$this->layout = false;
Copy after login

No need to render any view

$this->autoRender = false;
Copy after login

4. Define public methods/classes

Method 1:

You can define public methods in /app/Controller/AppController.php

Call

$this->test();
Copy after login

Method 2:

Create UtillComponent.php in /app/controllers/components

<?php
  class UtillComponent extends Object
  {
   function juanstr ($str) {
     return $str.&#39;+juanstr&#39;;
   }
  }
?>
Copy after login

Call:

var $components = array(&#39;Utill&#39;);
$digit1 = $this->Utill->juanstr($digit1);
Copy after login

5. Define prompt message

$this->Session->setFlash(__(&#39;The user has been saved&#39;));

<p class="wrong"><?php echo $this->Session->flash();?></p>
Copy after login

or

$this->Session->write(&#39;Message.auth&#39;,array(&#39;message&#39;=>__(&#39;The user has been saved.&#39;,true),&#39;element&#39;=>&#39;&#39;,&#39;params&#39;=>array()));

<p class="wrong"><?php echo $this->Session->flash(&#39;auth&#39;);?></p>
Copy after login

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(&#39;Subject&#39;,array(
  &#39;type&#39; => &#39;post&#39;,
  &#39;inputDefaults&#39;=>array(
    &#39;p&#39;=>false,
    &#39;label&#39;=>false
    ),
  &#39;url&#39;=>array(
      &#39;controller&#39;=>&#39;subjects&#39;,
      &#39;action&#39;=>&#39;edit&#39;
    ),
  &#39;onsubmit&#39;=>&#39;return validateCallback(this, dialogAjaxDone);&#39; //提交前验证
  )
);
echo $this->Form->input(&#39;id&#39;,array(&#39;type&#39;=>&#39;hidden&#39;));
echo $this->Form->input(&#39;uid&#39;,array(&#39;type&#39;=>&#39;hidden&#39;));
?>
<ul class="usr_info_basic">
<li>
  <p class="ti">下拉单选(编辑页面会自动判断选中)</p>
  <p class="ce">
<?php echo $this->Form->input(&#39;type&#39;,array(&#39;type&#39;=>&#39;select&#39; ,&#39;class&#39;=>&#39;ipt&#39;,&#39;options&#39; => array(0=>&#39;文章&#39;,1=>&#39;专题&#39;, 2=>&#39;图组&#39;)));?>
  </p>
</li>
<li>
  <p class="ti">多选</p>
  <p class="ce">
<?php
  echo $this->Form->input(&#39;pushtype&#39;, array(&#39;type&#39;=>&#39;select&#39;,
    &#39;options&#39; => $pushtype,//所有选项
    &#39;multiple&#39;=>&#39;checkbox&#39;,
    &#39;selected&#39; => $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();?>
Copy after login

##8. Log$this->log();

Call directly in the controller:

$this->log(&#39;Something brok2&#39;,LOG_DEBUG);
Copy after login

or call in the view:

Copy after login

The types of logs are roughly as follows:

$levels = array(
  LOG_WARNING=> &#39;warning&#39;,
  LOG_NOTICE=> &#39;notice&#39;,
  LOG_INFO=> &#39;info&#39;,
  LOG_DEBUG=> &#39;debug&#39;,
  LOG_ERR=> &#39;error&#39;,
  LOG_ERROR=> &#39;error&#39;
);
Copy after login

Log files are saved in the /app/tmp/logs directory.

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

define(&#39;LOG_ERROR&#39;, 2);
Copy after login

9. Rendering path

echo APP . &#39;webroot&#39; . DS;
//D:\wamp\www\cakephp\app\webroot\
echo APP . &#39;webroot&#39; ;
D:\wamp\www\cakephp\app\webroot
Copy after login

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 = &#39;Title of your page.&#39;; ?>
Copy after login

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[&#39;somedata&#39;] = array(&#39;some&#39;,&#39;data&#39;); ?>
Copy after login

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(&#39;CAKE_ADMIN&#39;, &#39;admin&#39;);
Copy after login

这样所有以"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; }
Copy after login

这样既能保持页面布局,又可以通过查看源代码来看到调试信息。当然最后发布网站时别忘了将调试级别改回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(&#39;Something broke&#39;);
Copy after login

这样可以将错误记录到 /tmp/logs/ 中(我最初以为会记录到apache的错误日志中)。

让controller使用其他model

如果你的controller需要调用来自不同model的数据,只要在controller开头使用如下代码:

class yourController extends AppController {
 var $uses = array(&#39;Post&#39;,&#39;User&#39;);
}
Copy after login

这样controller就能访问Post和User model了。

创建不使用数据库表的model

我需要创建一个不使用任何表的model。例如,我想通过$validate数组方便底验证输入数据,保持model逻辑的正确性。但创建model时对应的表不存在,CakePHP就会报错。通过在model中加入以下代码可以解决这个问题:

var $useTable = false;
Copy after login

你也可以通过这种方法改变model对应的表名。

var $useTable = &#39;some_table&#39;;
Copy after login

重定向之后记得exit()

对于有经验的人来说这应当是理所当然的事儿,调用 $this->redirect() 之后,剩下的代码如果不想运行要exit()。我也这样做,但以前曾经认为 $this->redirect() 会为我调用exit(实际上不会)。

高级model函数

翻翻API就能发现很多你不知道的非常有用的函数。我强烈推荐至少阅读一遍 Model 类的参考手册。下面是以前我没注意到的几个重要函数:

generateList() - 主要用于生成选择框(