利用ThinkPHP框架開發一個輕量級留言板,核心功能包含留言提交、表單驗證、分頁顯示。得益於框架封裝,控制器與模型代碼極其精簡。
class IndexAction extends Action {
public function index() {
$Form = M("word"); // 實例化模型
import("@.ORG.Page"); // 載入分頁類
$count = $Form->count(); // 總記錄數
$p = new Page($count, 1); // 每頁1條(演示用)
$list = $Form->limit($p->firstRow . ',' . $p->listRows)
->order('id desc')
->findAll();
$page = $p->show(); // 生成分頁導航
$this->assign("page", $page);
$this->assign("list", $list);
$this->display(); // 渲染模板
}
// 數據插入
public function insert() {
$word = D("word");
if ($vo = $word->create()) {
if (false !== $word->add()) {
$this->success("數據添加成功");
} else {
$this->error('數據寫入錯誤!');
}
} else {
$this->error($word->getError());
}
}
// AJAX驗證用戶名唯一性
public function checkTitle() {
if (!empty($_POST['username'])) {
$Form = M("word");
if ($Form->getByUsername($_POST['username'])) {
$this->error('<font color=red>標題已經存在</font>');
} else {
$this->success('標題可以使用!');
}
} else {
$this->error('標題必須');
}
}
}
class wordModel extends Model {
protected $_validate = array(
array('username', 'require', '稱呼必須!', 1),
array('email', 'email', '郵箱格式錯誤!', 2),
array('qq', 'number', 'QQ號錯誤', 2),
array('content', 'require', '內容必須', 1),
array('username', '', '稱呼已經存在', 0, 'unique', 1)
);
protected $_auto = array(
array('datetime', 'get_date', 1, 'callback'),
array('ip', 'getip', 1, 'callback')
);
protected function get_date() {
return date("Y-m-d H:i:s");
}
protected function getip() {
return $_SERVER['REMOTE_ADDR'];
}
}
ThinkPHP的CURD操作需注意表名規範,模型自動驗證與自動完成大幅減少控制器邏輯。更多框架技巧請參考專題《ThinkPHP常用方法總結》。