当前位置: 首页 > 编程文章 >

CakePHP博客系统核心代码与数据库结构示例

CakePHP博客系统核心代码与数据库结构示例

作者:江宁时间:2025-02-22 13:19:37浏览:844

本文提供基于CakePHP框架搭建简单博客系统的完整代码示例,涵盖PostsController控制器逻辑、Post模型定义、routes.php路由配置以及blog.sql数据库初始化脚本。该实例展示了从后端逻辑到数据结构的实现细节,适用于PHP开发者参考学习。

本文目录展开

CakePHP博客系统代码概览

本案例详细解析了利用CakePHP框架构建的简易博客平台,旨在为开发者提供可借鉴的实战方案。以下是具体的代码实现步骤与文件结构说明。

首先是PostsController.php控制器的实现代码:


<?php
class PostsController extends AppController {
 public $helpers = array('Html', 'Form', 'Session');
 public $components = array('Session');
 public function index() 
 {
   $this->set('posts', $this->Post->find('all'));
 }
 public function view($id=null)
 {
   $this->Post->id=$id;
   $this->set('post',$this->Post->read());
 }
 public function add()
 {
   if($this->request->is("post"))
   {
    $this->Post->create();
    if($this->Post->save($this->request->data))
    {
      $this->Session->setFlash("your post added!");
      $this->redirect(array('action'=>'index'));
    }
    else
    {
      $this->Session->setFlash("unable to create post!");
    }
   }
 }
 public function edit($id=null)
 {
   $this->Post->id=$id;
   if($this->request->is('get'))
   {
     $this->request->data = $this->Post->read();
   }
   else
   {
     if($this->Post->save($this->request->data)) 
     {
       $this->Session->setFlash('Your post has been updated.');
       $this->redirect(array('action' => 'index'));
     }
     else
     {
       $this->Session->setFlash('Unable to update your post.');
     }
   }
 }
 public function delete($id) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }
    if ($this->Post->delete($id)) {
      $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
 }
}
?>

接着是Post.php模型的实现代码:


<?php
class Post extends AppModel {
public $validate = array(
 'title' => array(
 'rule' => 'notEmpty'
),
 'body' => array(
 'rule' => 'notEmpty'
)
);
}
?>

然后是routes.php路由配置文件的内容:


<?php
/**
 * Routes configuration
 *
 * In this file, you set up routes to your controllers and their actions.
 * Routes are very important mechanism that allows you to freely connect
 * different urls to chosen controllers and their actions (functions).
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright   Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link     http://cakephp.org CakePHP(tm) Project
 * @package    app.Config
 * @since     CakePHP(tm) v 0.2.9
 * @license    MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * Here, we are connecting '/' (base path) to controller called 'Pages',
 * its action called 'display', and we pass a param to select the view file
 * to use (in this case, /app/View/Pages/home.ctp)...
 */
  //Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
  Router::connect('/', array('controller' => 'posts', 'action' => 'index'));
/**
 * ...and connect the rest of 'Pages' controller's urls.
 */
  Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
/**
 * Load all plugin routes. See the CakePlugin documentation on 
 * how to customize the loading of plugin routes.
 */
  CakePlugin::routes();
/**
 * Load the CakePHP default routes. Only remove this if you do not want to use
 * the built-in default routes.
 */
  require CAKE . 'Config' . DS . 'routes.php';

最后是用于初始化数据库的blog.sql脚本内容如下:


-- MySQL dump 10.13 Distrib 5.5.19, for Win64 (x86)
--
-- Host: localhost  Database: facebook
-- ------------------------------------------------------
-- Server version  5.5.19
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 
--
-- Table structure for table `posts`
--
DROP TABLE IF EXISTS `posts`;
/*!40101 SET @saved_cs_client   = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `posts` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `title` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
 `body` text COLLATE utf8_unicode_ci,
 `created` datetime DEFAULT NULL,
 `modified` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `posts`
--
LOCK TABLES `posts` WRITE;
/*!40000 ALTER TABLE `posts` DISABLE KEYS */;
INSERT INTO `posts` VALUES (1,'The title','This is the post body.','2012-11-01 15:43:41',NULL),(2,'A title once again','And the post body follows.','2012-11-01 15:43:41',NULL),(3,'Title strikes back','This is really exciting! Not.','2012-11-01 15:43:41',NULL),(4,'ggjjkhkhhk','7777777777777777777777777\r\n777777777777777777777777','2012-11-01 20:16:28','2012-11-01 20:16:28');
/*!40000 ALTER TABLE `posts` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `schema_migrations`
--
DROP TABLE IF EXISTS `schema_migrations`;
/*!40101 SET @saved_cs_client   = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `schema_migrations` (
 `version` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 UNIQUE KEY `unique_schema_migrations` (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `schema_migrations`
--
LOCK TABLES `schema_migrations` WRITE;
/*!40000 ALTER TABLE `schema_migrations` DISABLE KEYS */;
INSERT INTO `schema_migrations` VALUES ('20121013024711'),('20121013030850');
/*!40000 ALTER TABLE `schema_migrations` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2012-11-01 16:41:46

上述代码片段希望能对从事PHP程序设计的读者提供实质性的帮助。

上一篇
解决ThinkPHP路由开启后分页URL失效问题

在ThinkPHP 3.1.3及3.2.1版本中,启用路由功能后,系统默认的分页地址无法正确匹配路由规则,导致分页链接失效。该问题可通过修改核心文件functions.php中的U方法解决。具体做法是在生成URL参数拼接逻辑后,增加一段针对开启路由时的特殊处理代码,通过遍历URL_ROUTE_RULES将普通URL替换为对应的路由规则,从而确保分页链接符合路由定义。

下一篇
ThinkPHP集成阿里云OSS SDK指南

本文介绍在ThinkPHP框架中集成阿里云OSS PHP SDK的具体步骤。第三方库需放置于ThinkPHP/Library/Vendor/路径下,通过下载官方SDK并解压至该目录下的OSS文件夹完成安装。随后在控制器中使用Vendor函数引入autoload.php文件,实例化OssClient对象即可调用相关接口进行存储操作。

相关文章

更多
CakePHP配置数据库连接教程

在CakePHP框架中,数据库是不可或缺的核心组件。通过复制并重命名app/Config目录下的database.php.default模板文件为database.php,开发者可快速建立数据库连接。需重点修改login、password及database三项参数以匹配实际环境,确保服务器运行正常且用户具备操作权限即可完成基础配置。

2025.03.02 986
CakePHP框架Session设置与组件方法详解

CakePHP提供三种Session数据存储方式:临时文件、PHP默认机制及数据库序列化,默认采用PHP机制。若选数据库存储需执行/app/config/sql/sessions.sql脚本。Session Component默认可用于所有Controller,支持check、read、write、del等基础读写操作,以及setFlash管理Flash消息和renew更新会话ID,同时可通过error获取调试信息。

2026.04.05 872
配置Apache2.2+PHP5+CakePHP1.2+MySQL5运行环境

本文介绍如何在Windows环境下搭建基于Apache 2.2、PHP 5、CakePHP 1.2和MySQL 5的Web应用开发环境。重点涵盖Apache端口与模块配置、PHP模块加载及Mime类型设置、CakePHP目录结构与Rewrite规则调整,以及MySQL扩展启用和数据库连接配置等关键步骤,解决常见的缓存权限和DLL依赖问题。

2026.09.08 856
CakePHP 移除默认页面标题与图标及修改视图后缀

本文介绍如何在 CakePHP 中移除页面默认的标题和图标,通过修改 default.thtml 布局模板实现。同时说明如何将视图文件的默认扩展名从 .thtml 改为 .html,需在 controller.php 中调整 $ext 变量设置。

2025.06.27 613
PHP授权系统数据库结构设计与License生成算法

直接创建包含授权状态、过期时间、机器指纹和签名验证的数据库表,并使用 HMAC - SHA256 算法结合私钥生成 License 文件。

2026.01.24 606
CakePHP 基础教程:架构解析与配置指南

本文介绍 CakePHP 框架的基础知识、目录结构及核心配置。作为继承 Rails 优点的高效 PHP 框架,CakePHP 拥有清晰的 MVC 架构。文章详细解析了 app、cake、vendors 等核心文件夹的作用,并指导如何修改 bootstrap.php、core.php 中的常量设置,包括开启 Debug 模式排查错误、配置 Session 存储方式以及建立数据库连接,帮助初学者快速上手开发。

2026.02.12 550

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。