Cakephp 笔记

1. 自定义 layout

在 cakephp 中 layout 默认指向 /app/views/layouts/default.thtml
如果要自定义 layout,需要在 controller 中定义:
var $layout = 'mydefault';
layout 则指向了 /app/views/layouts/mydefault.thtml

2. 创建不使用数据库表的 model 或者改变 model 对应的表名

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

var $useTable = false;

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

var $useTable = 'some_table';

3. 快速创建后台管理

如果你需要创建后台管理程序,并且希望所有管理action都位于某个特定文件夹下,那么打开 config/core.php 并将下面这一行的注释去掉:

define('CAKE_ADMIN', 'admin');

这样所有以"admin_"开头的action都可以通过 /admin/yourcontroller/youraction 来访问。例如,如果在 posts controller 中创建了名为 "admin_add" 的 action,那么可以通过 www.example.com/admin/posts/add 访问这个action。这样就可以方便地为 admin 目录设置密码以避免他人随意访问。

4. 自定义404页面

如果你需要自定义404页面,只需创建 /app/views/errors/error404.thtml。

5. 让controller使用其他model

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

class yourController extends AppController {
var $uses = array('Post','User');
}

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

Tags: cakephp, framework, php, 笔记

相关日志

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)


*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comment moderation is enabled. Your comment may take some time to appear.