CakePHP应用开发:第五章 模型——数据的访问(1)
PHP动态网站开发实践教程课件第5章
5.3 案例:考试答题
5.3.1 案例呈现
在案例中主要实现以下功能: 1)显示考试答题页面。 2)通过PHP脚本获取用户提交的选项。 3)在页面显示用户提交的选项。
5.3 案例:考试答题
5.3.2 案例分析
根据案例的功能描述,可以将该案例的实现分为以下几个步骤: 1)创建考试答题页面,设置每个选项的name值。 2)给表单添加提交动作,单击“交卷”按钮跳转到PHP处理页面。 3)利用PHP脚本获取用户提交的选项,并显示在页面中。
"<br>"; }
谢 谢!
echo $sno; }
5.1 页面间参数传递
传递多个参数
<a href="edit.php?id=2018001&token=3869cd1251277241a5cc62ad477fc31d" >编辑</a> $sno = isset($_GET["id"]) ? $_GET["id"] : ""; $token = isset($_GET["token"]) ? $_GET["token"] : ""; if (!empty($sno) && !empty($token)) {
5.3 案例:考试答题
5.3.3 案例实现
1.创建考试答题页面——多选题 <div class="question-each">
<div>1. 下列选项中,不正确的是( )。</div> <div class="question-option">
PHP 5.0对象模型深度探索之访问方式
PHP 5.0对象模型深度探索之访问方式PHP5的访问方式允许限制对类成员的访问。
这是在PHP5中新增的功能,但在许多面向对象语言中都早已存在。
有了访问方式,才能开发一个可靠的面向对象应用程序,并且构建可重用的面向对象类库。
像C++和Java一样,PHP有三种访问方式:public,private和protected. 对于一个类成员的访问方式,可以是其中之一. 如果你没有指明访问方式,默认地访问方式为public. 你也可以为静态成员指明一种访问方式,将访问方式放在static关键字之前(如public static).Public成员可以被毫无限制地访问.类外部的任何代码都可以读写public属性. 你可以从脚本的任何地方调用一个public方法。
在PHP的前几个版本中,所有方法和属性都是public,这让人觉得对象就像是结构精巧的数组。
Private(私有)成员只在类的内部可见,你不能在一个private属性所在的类方法之外改变或读取它的值。
同样地,只有在同一个类中的方法可以调用一个private方法,继承的子类也不能访问父类中的private 成员。
要注意,类中的任何成员和类的实例都可以访问private成员。
看例子6.8,equals方法将两个widget进行比较.==运算符比较同一个类的两个对象,但这个例子中每个对象实例都有唯一的ID.equals方法只比较name和price。
注意equals方法如何访问另一个Widget 实例的private属性,Java和C都允许这样的操作。
Listing 6.8 Private membersclass Widget{private $name;private $price;private $id;public function __construct($name, $price){$this->name = $name;$this->price = floatval($price);$this->id = uniqid();}//checks if two widgets are the same 检查两个widget是否相同public function equals($widget){return(($this->name == $widget->name)AND ($this->price == $widget->price));}}$w1 = new Widget('Cog', 5.00);$w2 = new Widget('Cog', 5.00);$w3 = new Widget('Gear', 7.00);//TRUEif($w1->equals($w2)){print("w1 and w2 are the same n");}//FALSEif($w1->equals($w3)){print("w1 and w3 are the same n");}//FALSE, == includes id in comparisonif($w1 == $w2) //不等,因为ID不同{print("w1 and w2 are the same n");?>如果你对面向对象编程不熟悉,你可能想知道用private成员的目的是什么. 你可以回忆一下封装和耦合的想法,这在本章开头我们有讨论过。
cakephp简单示例
今天学了一下php,看到网上很多人推荐cakephp,就下载来试用了一下。
以下是我记录的笔记,入门级的。
如果我的理解和描述有不对的地方,请大家帮我指出来,谢谢!1、下载并安装cakephp∙cakephp官网:/∙或者/web/webmatrix/下载webmatrix,在这里安装cakephp。
2、创建数据库phptest,数据表users3、连接数据库,app/Config/database.phppublic$default=array('datasource'=>'Database/Mysql', //数据库类型'persistent'=>false,'host'=>'localhost', //主机名'login'=>'root', //用户名'password'=>'root', //密码'database'=>'phptest', //数据库名'prefix'=>''//'encoding' => 'utf8',);4、创建model,app/Model/User.php。
注意php有严格的命名规范,数据表用复数形式如users,model用表名的单数形式如user,则cakephp会自动关联users数据表、User模型、UsersController控制器和Users/***.ctp的视图。
<?phpclass User extends AppModel{var$name='User';//在 $name 中指定模型的名称是公认的最佳实践。
var$useTable='users';//这句可不要,默认是连接users数据表}?>5、创建控制器Controller,app/Controller/UsersController.php<?phpclass UsersController extends AppController{var$name='Users';function show(){$this->set('Users',$this->User->find('all'));//通过set函数把Users的值传给视图}}?>6、创建视图View,app/View/Users/show.ctp<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title></title></head><body><table><tr><th>id</th><th>username</th><th>password</th></tr><?php foreach($Users as $User):?><tr><td><?php echo $User['User']['id']; ?></td><td><?php echo $this->Html->link($User['User']['username'],"/Users/view/".$User['User']['id']); ?></td> <td><?php echo $User['User']['password']; ?></td></tr><?php endforeach;?></table></body></html>用table元素显示users列表,foreach($Users as $User)循环users对象,$User['模型名']['属性']获取对象的属性。
thinkphp5访客统计源码
thinkphp5访客统计源码摘要:一、引言二、ThinkPHP5访客统计原理1.数据统计方法2.数据存储与展示三、实现访客统计功能1.安装与配置2.代码编写3.测试与优化四、总结与展望正文:一、引言在网站运营过程中,对访客行为进行统计分析是非常重要的。
本文将介绍如何使用ThinkPHP5框架实现访客统计功能,为网站运营者提供有益的参考。
二、ThinkPHP5访客统计原理1.数据统计方法ThinkPHP5访客统计主要包括以下几个方面的数据:- 访客数量:当日访客、总访客数量- 访客来源:直接访问、搜索引擎、外部链接等- 访客地区:访客所在地区及访问来源- 访客行为:页面浏览、关键词搜索、留言等2.数据存储与展示- 数据存储:使用数据库存储访客统计数据,便于后期分析和导出- 数据展示:通过前端页面展示访客统计结果,支持图表、列表等形式三、实现访客统计功能1.安装与配置- 下载并安装ThinkPHP5框架- 配置数据库、权限等相关信息2.代码编写- 创建数据模型:根据访客统计需求,创建相应数据模型,如访客表、访客行为表等- 编写控制器:实现对访客数据的获取、处理、存储等功能- 编写前端页面:使用HTML、CSS、JavaScript等技术,展示访客统计数据3.测试与优化- 测试代码功能:确保访客统计功能正常运行,如数据获取、存储、展示等- 优化代码性能:针对性能瓶颈进行优化,提高系统响应速度四、总结与展望通过以上步骤,我们可以成功实现ThinkPHP5访客统计功能。
在实际应用过程中,根据网站需求,还可以增加更多访客统计指标,如访问时长、页面跳出率等。
php ppt课件
跨平台
PHP可以在多种操作系统上运行 ,如Linux、Unix、Windows等 。
社区支持
PHP拥有庞大的开发者社区,为 开发者提供了丰富的资源和支持 。
02 PHP基础语法
变量和数据类型
变量声明
PHP中的变量以美元符号($)开头,后跟变量名。例如,$name = "John";
数据类型
PHP支持多种数据类型,包括整数、浮点数、布尔值、字符串、数组、对象等 。例如,$age = 18; ($age 是整数类型),$price = 3.14; ($price 是浮点数类 型)。
开发一个博客系统
01
02
03
04
介绍如何使用PHP构建一个完 整的博客系统,包括文章管理 、评论管理、用户管理等。
演示如何使用PHP与数据库进 行交互,如MySQL或 MongoDB等。
讲解如何使用PHP进行数据验 证和安全性处理,如防止SQL
注入和跨站脚本攻击等。
介绍如何使用PHP进行文件上 传和下载,以及如何处理多媒
,扩展对象的行为。
04 PHP应用实例
简单的Web开发
01
介绍PHP在Web开发中 的应用,如动态网页、 表单处理、数据库交互 等。
02
演示一个简单的PHP网 站,包括登录、注册、 留言板等功能。
03
讲解PHP的常用函数和 语法,如echo、if语句 、循环语句等。
04
介绍PHP与HTML、CSS 、JavaScript的结合使 用,以及如何优化网页 性能。
体内容。
使用PHP进行数据分析和可视化
介绍如何使用PHP进行数据分析和可 视化,如使用PHP与图表库(如 Chart.js、ECharts等)结合。
CakePHP你必须知道的21条技巧
这篇文章可以说是CakePHP教程中最经典的了。
虽然不是完整的手把手系列,但作者将自己使用CakePHP的经验总结了21条,这些尤其是对新手十分有用。
翻译时故意保留了一些CakePHP中特有的词语没有翻译,如controller、model等。
相信学过CakePHP的人应该马上就能理解它们的意思吧。
另外,CakePHP的wiki已经失效,取而代之的是一个名为bakery的网站。
原文中引用的wiki的链接也都已更新到了bakery上。
快速创建静态页面我想建立几个页面,它们仅包含静态数据,使用默认layout,不需要任何model。
最初我试图创建一个controller并为每个静态页面定义一个action。
但这种方法很笨拙,也不适合快速创建静态页面。
实际上只要使用pages controller就可以做到——只要在views/pages 文件夹下创建一个view,就可以通过/pages 来访问。
例如,我创建了/views/pages/matt.thtml ,就可以通过/pages/matt来访问。
改变静态页面的标题使用pages controller时如果想改变页面标题,只需在view中加入以下代码:<? $this->pageTitle = 'Title of your page.'; ?>在静态页面中向layout发送数据如果需要向layout传递数据(例如表示导航栏中哪个部分应该高亮显示的变量),可以在view中添加下面的代码:<? $this->_viewVars['somedata'] = array('some','data'); ?>这个数组就可以在layout中通过$somedata来访问。
快速创建后台管理如果你需要创建后台管理程序,并且希望所有管理action都位于某个特定文件夹下,那么打开config/core.php 并将下面这一行的注释去掉:define('CAKE_ADMIN', 'admin');这样所有以"admin_"开头的action都可以通过/admin/yourcontroller/youraction 来访问。
PHP网站开发实例教程 第5章 内容管理系统(上)
第5章 内容管理系统(上)
PHP
• 项目展示 • 后台用户登录 • 验证码
• 后台页面搭建 • 栏目管理
✎
学习目标
1 掌握运用框架 进行项目开发 的方法
掌握在框架中对表单 2
进行处理的方法
掌握会话技术的 使用方法
4
掌握验证码功能
的开发方法
3
✎
目录
项目展示
☞点击查看本节相关知识点
</a></li> <li><a href="/admin/article/index" data-name="article">
<i class="fa fa-file-o fa-fw"></i>文章管理 </a> </li>
✎ 5.4 后台页面搭建
2 左侧菜单
✎ 5.4 后台页面搭建
3 后台首页
3 添加和修改栏目
✎ 5.5 栏目管理
4 删除栏目
➢ 点击 “删除”链接绑定单击事件,弹出确认框,提醒用户是否确认删除 ➢ 在控制器中编写delete()方法实现删除功能
✎ 5.2 后台用户登录
4 接收登录表单
验证用户名和密码是否正确: ➢ 根据用户名来查询用户的记录,判断用户是否存在 ➢ 如果用户存在,判断用户输入的密码是否正确 ➢ 用户名和密码正确,返回登录成功的信息,不正确则返回登录失败的信息
✎ 5.2 后台用户登录
5 判断登录状态
➢ 创建公共控制器,在公共控制器中进行登录的判断 ➢ 将用户的登录状态保存到Session中,如果没有用户信息自动跳转到登录页面 ➢ 不是所有的控制器和方法都要求用户必须登录,添加属性声明不需要登录的方法
cakePHP常用数据操作方法总结
CakePHP常用数据操作方法总结0.测试相关信息1.数据表(1)zmkm_testsId int(11) primary keyName char(10)Password char(32)Type tinyint(2)(2)zmkm_relationsId int(11) primary keyTest_id int(11)Content text2.Model:Test,Relation3.Controller:test,relation一.查询1.find($type,$params)I. $params,查询的限制条件,格式如下$params = array('conditions' => array('SQL中的where条件'),'fields' => array('查询字段'),'order' => array('排序字段,SQL中的order by 条件'),'group' => array('分组字段,SQL中的group by 条件'),'limit' => 'm,n', // 查询记录条数,SQL中limit'page' =>'n'// 还有recursive和callbacks等不常用的参数,略过);II.$type,查询的类型(1)$type = 'first',find的默认参数,查找符合条件的第一条数据.示例1: 查找数据表中第一条记录$lists = $this->Test->find();SQL:SELECT `Test`.`Id`, `Test`.`name`, `Test`.`password`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE 1 = 1 LIMIT 1结果: $lists = array(["Test"]=>array("Id"=>"1""name"=>"37892533""password"=>"2f441e566f1bbb7d1faaf32e85035048""type"=>"3"))示例2:查找一条type=1的记录$lists = $this->Test->find('first',array('conditions'=>array('Test.type' => '1')));SQL:SELECT `Test`.`Id`, `Test`.`name`, `Test`.`password`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `Test`.`type` = 1 LIMIT 1结果:$lists = array("Test"=>array("Id"=>"3""name"=>"37892533""password"=>"5997124ee980322f8a62a758dda4deee""type"=>"1"))(2)$type = 'all',查找所有符合条件的记录示例:查找所有type为[1,2,3]的记录$lists = $this->Test->find('all',array('conditions' => array('Test.type' => array('1','2','3'))));SQL:SELECT `Test`.`Id`, `Test`.`name`, `Test`.`password`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `Test`.`type` IN (1, 2, 3)结果:$lists = array(0 => array('Test'=>array('id'=>1,'name'=>.....)),1=>array(.....)...);(3)$type = 'list',返回一个索引数组,key第一列字段,若不指定fields,则value为第二列的字段示例:查找10<id<20 的记录,按type排序$condition = array('conditions'=>array('Test.id Between ? And ? ' => array(10,20)),'order' => 'Test.type desc');$lists = $this->Test->find('list',$condition);SQL:SELECT `Test`.`id`, `Test`.`name` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` Between 10 And 20 ORDER BY `Test`.`type` DESC结果: $lists = array('12' => '47192536' , '10'=>'68192536' , .....);(4)$type = 'count' , 计数,返回一个整数示例:查找type != (1,2) 的记录条数$con['conditions'] = array('not'=>array('Test.type' =>array(1,2)));$num = $this->Test->find('count',$con);SQL:SELECT COUNT(*) AS `count` FROM `zmkm_tests` AS `Test` WHERE NOT (`Test`.`type` IN (1, 2))结果: int(14)(5)$type = 'neighbors',查询符合条件的记录的前后两条记录示例:查找id=33 且满足type<3 的前后两条记录$condition = array('field' => 'id', // * (必须筛选字段)'value' => '33', // * (必须field的值)'conditions' => array('type < ' => '3'),'fields'=> 'id,name,type', // * (必须查找字段));$lists = $this->Test->find('neighbors',$condition);SQL:执行两条SQL:Query: SELECT `Test`.`id`, `Test`.`name`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `type` < 3 AND `Test`.`id` < '33' ORDER BY `Test`.`id` DESC LIMIT 1 Query: SELECT `Test`.`id`, `Test`.`name`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `type` < 3 AND `Test`.`id` > '33' ORDER BY `Test`.`id` ASC LIMIT 1结果:array(2) {"prev"=> array("Test"=>rray("id"=>"32","name"=>"44392536","type"=>"2"))"next"=> array("Test"=>array("id"=>"39","name"=>"14292536","type"=>"1")))2.findByField($params):通过字段查找记录,只返回一条记录,函数名需要用驼峰式书写示例1:通过数据表中的id查找$lists = $this->Test->findById('3');SQL:SELECT `Test`.`Id`, `Test`.`name`, `Test`.`password`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` ='3' LIMIT 1结果:略示例2:通过数据表中的type查找$lists = $this->Test->findByType(array('3','5','7'));SQL:SELECT `Test`.`Id`, `Test`.`name`, `Test`.`password`, `Test`.`type` FROM `zmkm_tests` AS `Test` WHERE `Test`.`type` IN ('3', '5', '7') LIMIT 1结果:略注:对于数据表中类似"user_status"的字段,方法名为findByUserStatus()3.Field($field,$condition),查找一个字段,函数返回字段值示例:查找id=34的password$password = $this->Test->field('password',array('Test.id'=>'34'));SQL:SELECT `Test`.`password` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` = '34' LIMIT 1 结果: string(32) "2f441e566f1bbb7d1faaf32e85035048"二.添加数据1.save($data),插入一条记录,返回以model名为key值的$data数组(1).$data中无数据表的主键对应的字段值,则插入一条新纪录示例:插入一条记录$data = array('name' => 'zhongsou','passowrd' => md5(time()),'type' => rand(0,9));$this->Test->save($data);$lastInsertId = $this->Test->id; // 插入的一条记录的idSQL:INSERT INTO `zmkm_tests` (`name`, `password`, `type`) VALUES('zhongsou', '0674ab9bda247f85a5e4aa49ecb73b38', 9)注:如果$data中存在数据表中没有的字段,则插入时忽略(2).saveAll($data),插入单个模型的多条记录,或者是该模型的关联记录A. 向同一个model插入多条记录,在cakePHP手册中介绍有误,$data数组的格式应该如下:$data = array('0' => array('name' => 'abc' , 'password' => 'b2c'),'1' => array('name' => '123' , 'password' => 'p2p'));或者:$data = array('0' => array('Test' =>array('name' => 'abc' , 'password' => 'b2c') ),'1' => array('Test' => array('name' => '123' , 'password' => 'p2p') ));SQL:执行多条insert语句B.插入关联记录,新建关联表M_relation,test_id为外键,关联M_test(id),关联关系为一对一(hasOne),关联关系需要在model中定义,$data数据格式$data = array('Relation' => array('test_id' => 3020,'content' => ''),'Test' => array('id' => 3020,'name' => 'zhongsou','password' => md5(time()),'type' => 1));$this->Relation->saveAll($data);SQL:显示的事务处理,在MyISAM引擎中同样可用1.START TRANSACTION2.INSERT INTO `M_relations` (`test_id`, `content`) VALUES (111,'')3.SELECT LAST_INSERT_ID() AS insertID4.SELECT COUNT(*) AS `count` FROM `zmkm_tests` AS `Test` WHERE`Test`.`id` = 1115.INSERT INTO `zmkm_tests` (`name`, `password`, `type`) VALUES ('zhongsou','7248ba8995187e38f404239f787d252c', 1)7.SELECT LAST_INSERT_ID() AS insertIDMIT(3).$data中有数据表的主键对应的字段值,则修改该记录的相应字段值$data['Test'] = array('id' => '78','name' => 'zhongsou','password' => md5(time()),'type' => rand(0,9));$this->Test->save($data);$updataId = $this->Test->id; // 修改的记录的idSQL:执行两条SQL,进行插入和更新的判断SELECT COUNT(*) AS `count` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` = '78'UPDATE `zmkm_tests` SET `name` = 'zhongsou', `password` = '2816c19a87b69d758799054dc8b4cc2e', `type` = 9 WHERE`zmkm_tests`.`id` = '78'三.修改1.updateAll($data,$condition),更改所有符合条件的记录示例:修改name字段$data = array('name' => "'souhu'");$condition = array('' => 'zhongsou');$result = $this->Test->updateAll($data,$condition);SQL:UPDATE `zmkm_tests` AS `Test` SET `Test`.`name` = 'souhu' WHERE 'Test'.`name` = 'zhongsou'2.saveField('field',$value),修改一个字段值,需要先指定id示例:修改id=89 的name$this->Test->id = 89;$this->Test->saveField('name','other');SQL:UPDATE `zmkm_tests` SET `name` = 'other' WHERE `zmkm_tests`.`id` = 89四.删除1.delete(),删除一条记录,需要先指定id,返回boolean示例:删除id=105的记录$this->Test->id = '106';$result = $this->Test->delete();SQL:SELECT COUNT(*) AS `count` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` = '106'DELETE `Test` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` = '106'2.deleteAll($condition),删除多条记录,$condition为删除条件示例:删除id>100 & type != [1,2,3] 的记录$condition = array('id >' => 100,'not' => array('type'=>array('1','2','3')));$this->Test->deleteAll($condition );SQL: 分成两条SQL执行的SELECT `Test`.`id` FROM `zmkm_tests` AS `Test` WHERE `id` > 100 AND NOT (type IN (1, 2, 3))DELETE `Test` FROM `zmkm_tests` AS `Test` WHERE `Test`.`id` IN ('102', '103', '104')附:若把cakePHP的debug设为2依然无法在页面上打印SQL语句,则可以通过调用如下方法:/*** 获取SQL执行的日志* return array*/function printSQL(){$sources = ConnectionManager::sourceList();$logs = array();foreach ($sources as $source){$db =& ConnectionManager::getDataSource($source);if (!$db->isInterfaceSupported('getLog')) continue;$logs[$source] = $db->getLog();}return $logs;}。
CakePHP 实例教程 Categories Acts as Tree
Tree是CakePHP1.2的核心Behaviors之一,可以用来轻易的实现无限极分类,并呈现树状列表。
图片来源:Tree traversa,WIKIPEDIA基础实例建立数据表CREATE TABLE`categories`(`id`INT(11)NOT NULL AUTO_INCREMENT,`name`VARCHAR(255)NOT NULL,`slug`VARCHAR(255)NOT NULL,`parent_id`INT(11)DEFAULT NULL,`lft`INT(11)DEFAULT NULL,`rght`INT(11)DEFAULT NULL,`link_count`INT(11)NOT NULL DEFAULT'0',PRIMARY KEY(`id`))DEFAULT CHARSET=utf8;字段说明:parent_id,lft,rght均为必要字段,parent_id是很常用的表层级关系的做法。
但在这里,lft和rght才是重点。
它们表示的是一个分类的左右边界。
原理如下图所示图片来源:Managing Hierarchical Data in MySQL, 建立Model使用bake shell$cd app$cake bakeCategory Model:class Category extends AppModel{var$name='Category';var$actsAs=array('Tree');}Categories Controller:class CategoriesController extends AppController{ var$name='Categories';}Add Actionfunction add(){if(!empty($this->data)){$this->Category->create();if($this->Category->save($this->data)){$this->Session->setFlash(__('The Category has been saved', true));$this->redirect(array('action'=>'index'));}else{$this->Session->setFlash(__('The Category could not be saved. Please,try again.',true));}}$this->set('categories',$this->Category->generatetreelist(null,null, null,'--'));}add.ctp<?php$form->create('Category');?><fieldset><legend><?php__('Add Category');?></legend><?php$form->input('name');?><?php$form->input('slug');?><?php$form->select('parent_id',$categories);?></fieldset><?php$form->end('Submit');?>更进一步取得层级分类class Category extends AppModel{var$name='Category';var$actsAs=array('Tree');function getThreadCategories(){$this->recursive=-1;return$this->findAllThreaded(null,null,'lft asc');}}取得下属条目当给分类下添加条目,比如Links时,基本的做法是class Category extends AppModel{var$name='Category';var$hasMany=array('Links'=>array('className'=>'Link','foreignKey'=>'category_id',));}这样就通过Link.category_id连接了Link和对应的Category。
CakePHP应用开发:第五章 模型——数据的访问(2.设置数据库和模型)
CakePHP应用开发:第五章模型——数据的访问(2.设置数据库和模型)我们已经知道,模型类通常都是用来与数据库进行互动的。
在CakePHP中,一个模型类通常都对应数据库中的莫个表。
所有对表进行的数据库操作都是通过对应的模型类来实施的。
CakePHP的模型与数据库表之间的对应关系无需设置。
相反,CakePHP使用了一些简单的命名规则来实现这一效果,在这一部分,我们将了解到如何为数据库中的表的创建对已的模型类。
CakePHP提供了一个名为"脚手架"工具来帮助我们检查先前创建好的模型和数据库表。
我们也将了解到如何使用“脚手架”功能完成这一工作。
为数据库中的表创建模型在了解模型类是如何与数据库表进行互动之前,我们首先要创建一个数据库表。
在接下来这一部分中,我们首先将创建一个数据库表,然后了解如何为这个表创建一个模型类。
然后我们也会使用脚手架功能对新创建的模型和数据表进行一个快速的测试。
l动手时间:创建一个数据库表以及对应的模型1,在MySQL命令提示行中,我们输入如下数据库命令来创建一个名为data-Access的新数据库。
CREATE DATABASE`data-access`;2,通过执行下面的SQL语句来创建一个“books”表:USE`data-access`;CREATE TABLE`books`(`id`int(11)NOT NULL AUTO_INCREMENT PRIMARY KEY,`isbn`varchar(10)NOT NULL,`title`varchar(127)NOT NULL,`description`text NOT NULL,`author_name`varchar(127)NOT NULL)3,将一份全新的CakePHP文件夹放置到你的网页根目录下。
将Cake的文件夹重命名为data-access.4,进入Cake安装文件夹下的/app/config目录。
15分钟使用CakePHP创建一个简单的博客
•既然要看文档为什么不看英文文档呢?所以自己翻译了CakePHP手册里的这篇文章,翻得很烂,权当自己学习的记录。
原文地址:/view/219/Blog1准备欢迎来到CakePHP的世界!你也许正在看这篇指导文章,因为你想更多地了解CakePHP是如何工作的。
我们的目标就是增加程序的生产效率并且让代码更有趣:我们希望当你编写代码的时候会明白这一点。
这篇文章将带你创建一个简单的博客程序。
我们将先获得并安装CakePHP,然后配置一个数据库,接着创建一个能够展示、添加、编辑并且删除文章的程序。
下面这些是你所需要的:1.一个正在运行的WEB服务器。
尽管下面的介绍对于其他服务器软件来说都是相似的,但再这里我们假定你正在使用Apache。
我们可能会对服务器做一些配置,但是对于大多数人完全可以运行CakePHP而不用做任何配置。
2.一个数据库程序。
在这篇文章里,我们将使用mySQL。
你需要有足够的SQL知识来创建一个数据库:CakePHP将操作它。
3.基本的PHP知识。
特别是对于OOP的了解越多越好:但是也别担心,如果你是一个程序爱好者的话。
4.最后,你需要一些MVC方面的基本知识。
你也可以快速的看一下这篇文章:《理解Model-View-Controller》。
下面就让我们开始吧。
1.1获得CakePHP首先,让我们获得一个新的CakePHP拷贝。
访问在Cakeforge上的CakePHP项目:/projects/cakephp/下载稳定版本。
在这里你需要1.2.x.x你也可以查看/导出一个新的拷贝在我们的trun上:https:///repo/trunk/cake/1.2.x.x/不管你是怎么下载它的,把它放到你自己的文档目录里。
这些完成后你的目录看起来应该是下面这个样子的:/path_to_document_root/app/cake/docs/vendors.htaccessindex.php现在正是可以学习下CakePHP的目录结构是如何工作的:查看《CakePHP 文件结构》。
Cakephp学习总结及问题汇总
Cakephp学习总结及问题汇总⽬录1 Beginning With CakePHP (2)1.1 What is CakePHP? Why Use it? (2)1.3 Understanding Model-View-Controller (3)2 Basic Principles of CakePHP (4)2.1 CakePHP Structure (4)2.1.1 Controller Extensions ("Components") (4)2.1.2 View Extensions ("Helpers") (4)2.1.3 Model Extensions ("Behaviors") (4)2.1.4 Application Extensions (4)2.2 A Typical CakePHP Request (5)2.3 CakePHP Folder Structure (6)2.3.1 The App Folder (6)2.4 CakePHP Conventions (6)2.4.1 File and Classname Conventions (6)3 Developing with CakePHP (7)3.3 Installation (7)3.3.3 Advanced Installation (7)3.3.4 Apache and mod_rewrite (and .htaccess) (7)4 Common Tasks With CakePHP (11)4.7 Testing (11)4.7.1 Preparing for testing (11)4.7.2 Testing overview - Unit testing vs. Web testing (12)4.7.3 Preparing test data (12)4.7.4 Creating tests (14)4.7.5 Testing models (15)4.7.6 Testing controllers (15)4.7.9 Web testing - Testing views (16)5 Core Components (17)5.1 Access Control Lists (17)5.1.1 Understanding How ACL Works (17)8 Core Utility Libraries (17)8.1 Inflector (17)10 Tutorials & Examples (18)10.1.4 Optional Configuration (18)10.1.13 Routes (18)3.10.2 Layouts (18)10 处理乱码 (18)CakePHP你必须知道的21条技巧 (18)改变页⾯标题 (18)向layout传数据 (18)查看后台执⾏SQL (19)获取丰富的开发⽂档:Wiki和API (19)使⽤bake.php (19)发布程序时要修改app/tmp的权限:对apache可写 (19)复杂model验证 (19)记录错误⽇志 (19)让Controller使⽤其他Model (19)重定向后要exit(); (19)⾼级model函数 (19)为cakePHP添加所见即所地编辑器 (20)通过PHPMailer发送邮件 (20)⾃定义Helper⽣成的HTML (20)⾃定义404页⾯:只需要创建/app/views/errors/error404.thtml (20) 1 Beginning With CakePHP1.1 What is CakePHP? Why Use it?Here’s a quick list of features you’ll enjoy when using CakePHP:Active, friendly communityFlexible licensingCompatible with versions 4 and 5 of PHPIntegrated CRUD for database interactionApplication scaffoldingCode generationMVC architectureRequest dispatcher with clean, custom URLs and routesBuilt-in validationFast and flexible templating (PHP syntax, with helpers)View Helpers for AJAX, JavaScript, HTML Forms and moreEmail, Cookie, Security, Session, and Request Handling ComponentsFlexible ACLData SanitizationFlexible CachingLocalizationWorks from any web site directory, with little to no Apache configuration involved1.3 Understanding Model-View-Controller1.The Model represents the application data2.The View renders a presentation of model data3.The Controller handles and routes requests made by the client2 Basic Principles of CakePHP2.1 CakePHP Structure2.1.1 Controller Extensions ("Components")A Component is a class that aids in controller logic. If you have some logic you want to share between controllers (or applications), a component is usually a good fit.Controllers are also fitted with callbacks.beforeFilter(), executed before any controller action logicbeforeRender(), executed after controller logic, but before the view is rendered afterFilter(), executed after all controller logic, including the view render.There may be no difference between afterRender() and afterFilter() unless you’ve manually made a call to render() in your controller action and haveincluded some logic after that call.2.1.2 View Extensions ("Helpers")A Helper is a class that aids in view logic. Much like a component used among controllers, helpers allow presentational logic to be accessed and shared between views. One of the core helpers, AjaxHelper, makes Ajax requests within views much easier.Most applications have pieces of view code that are used repeatedly. CakePHP facilitates view code reuse with layouts and elements. By default, every view rendered by a controller is placed inside a layout. Elements are used when small snippets of content need to be reused in multiple views.2.1.3 Model Extensions ("Behaviors")Behaviors work as ways to add common functionality between models.models are featured with callbacks as well:beforeFind()afterFind()beforeValidate()beforeSave()afterSave()beforeDelete()afterDelete()2.1.4 Application ExtensionsControllers, helpers and models each have a parent class you can use to define application-wide changes. AppController (located at /app/app_controller.php), AppHelper (located at/app/app_helper.php) and AppModel (located at /app/app_model.php) are great places to put methods you want to share between all controllers, helpers or models.2.2 A Typical CakePHP Request1.Ricardo clicks the link pointing to /doc/0c12e0a0284ac850ad0242d2.html /cakes/buy, and hisbrowser makes a request to your web server.2.The Router parses the URL in order to extract the parameters for this request: thecontroller, action, and any other arguments that will affect the business logicduring this request./doc/0c12e0a0284ac850ad0242d2.html ing routes, a request URL is mapped to a controller action (a method in aspecific controller class). In this case, it’s the buy() method of theCakesController. The controller’s beforeFilter() callback is called before anycontroller action logic is executed.4.The controller may use models to gain access to the application’s data. In thisexample, the controller uses a model to fetch Ricardo’s last purchases from thedatabase. Any applicable model callbacks, behaviors, and DataSources may apply during this operation. While model usage is not required, all CakePHP controllers initially require at least one model.5.After the model has retrieved the data, it is returned to the controller. Modelcallbacks may apply.6.The controller may use components to further refine the data or perform otheroperations (session manipulation, authentication, or sending emails, for example).7.Once the controller has used models and components to prepare the datasufficiently, that data is handed to the view using the controller’s set() method.Controller callbacks may be applied before the data is sent. The view logic isperformed, which may include the use of elements and/or helpers. By default, the view is rendered inside of a layout.8.Additional controller callbacks (like afterFilter) may be applied. The complete,rendered view code is sent to Ricardo’s browser.2.3 CakePHP Folder Structure2.3.1 The App Folderconfig Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.controllers Contains your application’s controllers and their components.locale Stores string files for internationalization.models Contains your application’s models, behaviors, and datasources. plugins Contains plugin packages.tmp This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information. Make sure that this folder exists and that it is writable, otherwise the performance of your application will be severely impacted. In debug mode, CakePHP will warn you if it is not the case.vendors Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the App::import('vendor', 'name') function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure. We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups.views Presentational files are placed here: elements, error pages, helpers, layouts, and view files.webroot In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.2.4 CakePHP Conventions2.4.1 File and Classname ConventionsThe Controller class KissesAndHugsController would be found in a file named kisses_and_hugs_controller.php (notice _controller in the filename) The Component class MyHandyComponent would be found in a file named my_handy.phpThe Model class OptionValue would be found in a file namedoption_value.phpThe Behavior class EspeciallyFunkableBehavior would be found in a file named especially_funkable.phpThe View class SuperSimpleView would be found in a file namedsuper_simple.phpThe Helper class BestEverHelper would be found in a file namedbest_ever.phpThe Inflector class takes a string and can manipulate it to handle word variations such as pluralizations or camelizing and is normally accessed statically. Example:Inflector::pluralize('example') returns "examples".3 Developing with CakePHP3.3 Installation3.3.3 Advanced InstallationTo configure your Cake installation, you'll need to make some changes to/app/webroot/index.php. There are three constants that you'll need to edit: ROOT,APP_DIR, and CAKE_CORE_INCLUDE_PATH.ROOT should be set to the path of the directory that contains your app folder.APP_DIR should be set to the (base)name of your app folder.CAKE_CORE_INCLUDE_PATH should be set to the path of your CakePHP libraries folder.3.3.3.1 Additional Class Pathsyou can use CakeP HP’s bootstrap.php to bring these additional classes into view.3.3.4 Apache and mod_rewrite (and .htaccess)3.15 Global Constants and Functions3.15.1 Global Functions3.15.1.1 ____(string $string_id, boolean $return = false)3.15.1.2 aprint_r(a('foo', 'bar'));// output:array([0] => 'foo',[1] => 'bar')3.15.1.3 aaprint_r(aa('a','b'));// output:array('a' => 'b')3.15.1.4 amam(array $one, $two, $three...)3.15.1.5 configCan be used to load files from your application config-folder via include_once. Function checks for existance before include and returns boolean. Takes an optional number of arguments. Example: config('some_file', 'myconfig');3.15.1.6 convertSlashconvertSlash(string $string)Converts forward slashes to underscores and removes the first and last underscores in a string. Returns the converted string.3.15.1.7 debugdebug(mixed $var, boolean $showHtml = false)If the application's DEBUG level is non-zero, $var is printed out. If $showHTML is true, the data is rendered to be browser-friendly.Also see Basic Debugging3.15.1.8 eConvenience wrapper for echo().This has been Deprecated and will be removed in 2.0 version. Use echo() instead3.15.1.9 envenv(string $key)Gets an environment variable from available sources. Used as a backup if $_SERVER or $_ENV are disabled.This function also emulates PHP_SELF and DOCUMENT_ROOT on unsupporting servers. In fact, it's a good idea to always use env() instead of $_SERVER or getenv() (especially if you plan to distribute the code), since it's a full emulation wrapper.3.15.1.10 fileExistsInPathfileExistsInPath(string $file)Checks to make sure that the supplied file is within the current PHP include_path. Returns a boolean result.3.15.1.11 hh(string $text, string $charset = null)Convenience wrapper for htmlspecialchars().ife($condition, $ifNotEmpty, $ifEmpty)Used for ternary-like operations. If the $condition is non-empty, $ifNotEmpty is returned, else $ifEmpty is returned.This has been Deprecated and will be removed in 2.0 version.3.15.1.13 lowlow(string $string)Convenience wrapper for strtolower().This has been Deprecated and will be removed in 2.0 version. Use strtolower() instead3.15.1.14 prpr(mixed $var)Convenience wrapper for print_r(), with the addition of wrappingtags around the output.3.15.1.15 rr(string $search, string $replace, string $subject)Convenience wrapper for str_replace().This has been Deprecated and will be removed in 2.0 version. Use str_replace() instead 3.15.1.16 stripslashes_deepstripslashes_deep(array $value)Recursively strips slashes from the supplied $value. Returns the modified array.3.15.1.17 upup(string $string)Convenience wrapper for strtoupper().This has been Deprecated and will be removed in 2.0 version. Use strtoupper() instead 3.15.1.18 usesuses(string $lib1, $lib2, $lib3...)Used to load CakePHP's core libraries (found in cake/libs/). Supply the name of the library's file name without the '.php' extension.This has been Deprecated and will be removed in 2.0 version.3.15.2 Core Definition Constantsconstant Abso lute path to the application’s...APP root directory.APP_PATH app directory.CACHE cache files directory.CAKE cake directory.COMPONENTS components directory.CONFIGS configuration files directory.CONTROLLER_TESTS c ontroller tests directory.CONTROLLERS controllers directory.CSS CSS files directory.DS Short for PHP's DIRECTORY_SEPARATOR, which is / onLinux and \ on windows.ELEMENTS elements directory.HELPER_TESTS helper tests directory.HELPERS helpers directory.IMAGES images directory.JS JavaScript files directory (in the webroot).LAYOUTS layouts directory.LIB_TESTS CakePHP Library tests directory.LIBS CakePHP libs directory.LOGS logs directory (in app).MODEL_TESTS model tests directory.MODELS models directory.SCRIPTS Cake scripts directory.TESTS tests directory (parent for the models, controllers, etc. testdirectories)TMP tmp directory.VENDORS vendors directory.VIEWS views directory.WWW_ROOT full path to the webroot.4 Common Tasks With CakePHP4.7 Testing4.7.1 Preparing for testing4.7.1.1 Installing SimpleTestWe need to download it first. You can find it here: /doc/0c12e0a0284ac850ad0242d2.html /. unzip the code to your vendors folder, or your app/vendors folder Remember to have a DEBUG level of at least 1 in your app/config/core.php file before running any tests!create a $test database connection to contain any test tables, inapp/config/database.php,var $test = array('driver' => 'mysql','persistent' => false,'login' => 'dblogin','password' => 'dbpassword','database' => 'databaseName' );4.7.1.2 Running Core test casesTo add the core tests to your existing applicationLocate the /cake/tests directory from the repository and copy it (recursively) into your/cake/tests folder.See: http://your.cake.domain/test.php4.7.2 Testing overview - Unit testing vs. Web testingtwo types of testing: Unit testing vs. Web testing4.7.3 Preparing test dataCakePHP performs the following during the course of a fixture based test case:1.Creates tables for each of the fixtures needed2.Populates tables with data, if data is provided in fixture3.Runs test methods4.Empties the fixture tables5.Removes fixture tables from databaseWhen creating a fixture you will mainly define two things: how the table is created (which fields are part of the table), and which records will be initially populated to the test table. You can create new fixture or import from existed tables.4.7.3.3 Importing table information and recordsapp/tests/fixtures/article_fixture.phpImport model:1.2.class ArticleFixture extends CakeTestFixture {3.var $name = 'Article';4.var $import = 'Article';5.}6.?>Import model and data:class ArticleFixture extends CakeTestFixture {var $name = 'Article';var $import = array('model' => 'Article', 'records' => true);}>Import table:1.2.class ArticleFixture extends CakeTestFixture {3.var $name = 'Article';4.var $import = array('table' => 'articles');5.}6.?>Import table from other database:1.2.class ArticleFixture extends CakeTestFixture {3.var $name = 'Article';4.var $import = array('table' => 'articles', 'connection' =>'other');5.}6.?>Import table and data:1.2.class ArticleFixture extends CakeTestFixture {3.var $name = 'Article';4.var $import = array('table' => 'articles', 'records' => true);5.}6.?>Import model and your own data:1.class ArticleFixture extends CakeTestFixture {2.var $name = 'Article';3.var $import = 'Article';4.5.var $records = array(6.array ('id' => 1, 'title' => 'First Article', 'body' => 'FirstArticle Body', 'published' => '1', 'created' => '2007-03-1810:39:23', 'updated' => '2007-03-18 10:41:31'),7.array ('id' => 2, 'title' => 'Second Article', 'body' => 'SecondArticle Body', 'published' => '1', 'created' => '2007-03-1810:41:23', 'updated' => '2007-03-18 10:43:31'),8.array ('id' => 3, 'title' => 'Third Article', 'body' => 'ThirdArticle Body', 'published' => '1', 'created' => '2007-03-1810:43:23', 'updated' => '2007-03-18 10:45:31')9.);10.}11.?>4.7.4 Creating testsFirst, lets go through a number of rules, or guidelines, concerning tests:1.PHP files containing tests should be in your app/tests/cases/[some_folder].2.The filenames of these files should end in .test.php instead of just .php.3.The classes containing tests should extend CakeTestCase or CakeWebTestCase.4.The name of any method containing a test (i.e. containing an assertion) shouldbegin with test, as in testPublished().When you have created a test case, you can execute it by browsing tohttp://your.cake.domain/cake_folder/test.php (depending on how your specific setup looks) and clicking App test cases, and then click the link to your specific file.4.7.4.1 CakeTestCase Callback Methodsstart()First method called in a test case.end()Last method called in a test case.startCase()called before a test case is started.endCase()called after a test case has run.before($method)Announces the start of a test method.after($method)Announces the end of a test method.startTest($method)Called just before a test method is executed.endTest($method)Called just after a test method has completed.4.7.5 Testing modelscreate a file named article.test.php in your app/tests/cases/models directoryApp::import ( 'Model', 'Article' );class ArticleTestCase extends CakeTestCase {var $fixtures = array ('app.article' );function testFindAll() {//实例化Model$this->Department = & ClassRegistry::init ( 'Department' );//调⽤⽅法$result = $this->Department->find ( 'all' );//设置期望值$expected = array(array('Article' => array( 'id' => 1, 'title' => 'First Article' )), array('Article' => array( 'id' => 2, 'title' => 'Second Article' )), array('Article' => array( 'id' => 3, 'title' => 'Third Article' )) );//对⽐结果$this->assertEqual ( $result, $expected );}}>If your model is associated with other models, you will need to include ALL the fixtures for eachassociated model even if you don't use them. For example: A hasMany B hasMany C hasMany D.In ATestCase you will have to include fixtures for a, b, c and d.4.7.6 Testing controllersCreate a file named articles_controller.test.php in your app/tests/cases/controllers directoryclass ArticlesControllerTest extends CakeTestCase {function startCase() {echo 'Starting Test Case';}function endCase() {echo 'Ending Test Case';}function startTest($method) {echo 'Starting method ' . $method . '';}function endTest($method) {echo '';}function testIndex() {$result = $this->testAction ( '/departments/index' );debug ( $result );}function testIndexShort() {$result = $this->testAction ( '/departments/index/short' );debug ( $result );}function testIndexShortGetRenderedHtml() {$result = $this->testAction ( '/departments/index/short', array ('return' => 'render' ) );debug ( htmlentities ( $result ) );}function testIndexShortGetViewVars() {$result = $this->testAction ( '/departments/index/short', array ('return' => 'vars' ) );debug ( $result );}function testIndexFixturized() {$result = $this->testAction ( '/departments/index/short', array ('fixturize' => true ) );debug ( $result );}function testIndexPostFixturized() {$data = array ('Article' => array ('user_id' => 1,'published' => 1, 'slug' => 'new-article', 'title' => 'New Article','body' => 'New Body' ) );$result = $this->testAction ( '/departments/index', array ('fixturize' => true, 'data' => $data, 'method' => 'post' ) );debug ( $result );}}>If you use testAction to test a method in a controller that does a redirect, your test will terminate immediately, not yielding any results.4.7.9 Web testing - Testing viewsall web test cases involving updating/saving to the database will permanently change your database values4.7.9.2 Creating a testcreate the file tests/cases/views/complete_web.test.php5 Core Components5.1 Access Control Lists5.1.1 Understanding How ACL WorksTo review:ACO - Access Control Object - Something that is wantedARO - Access Request Object - Something that wants somethingACOs could be anything you want to control, from a controller action, to a web service, to a line on your grandma's online diary.Essentially, ACL is what is used to decide when an ARO can have access to an ACO.Realize that ACL is not the same as authentication. ACL is what happens after a user has been authenticated. Although the two are usually used in concert, it's important to realize the difference between knowing who someone is (authentication) and knowing w 5.1.3 Defining Permissions: Cake's Database ACL/doc/0c12e0a0284ac850ad0242d2.html /view/1245/Defining-Permissions-Cake-s-Database-ACL参考/doc/0c12e0a0284ac850ad0242d2.html /thread-1611367-1-1.html(cakephp中acl和auth详解 - Php - ChinaUnix_net.mht)1.cake schema create DbAcl8 Core Utility Libraries8.1 InflectorThe Inflector class takes a string and can manipulate it to handle word variations such as pluralizations or camelizing and is normally accessed statically. Example:Inflector::pluralize('example') returns "examples".9 Core Console Applications9.1 Code Generation with Bakecake bake10 Tutorials & Examples10.1.4 Optional Configuration/app/config/core.php1.2./**3.* A random string used in security hashing methods.4.*/5.Configure::write('Security.salt', 'pl345e-P45s_7h3*S@l7!');6.?>10.1.13 Routes/app/config/routes.phpRouter::connect ('/', array('controller'=>'posts', 'action'=>'index'));3.10.2 LayoutsCakePHP's default layout can be overridden by creating a new default layout/app/views/layouts/default.ctp10 处理乱码理乱码只要遵循这个原则就⾏了:数据库的编码,\cake\app\config\database.php的encoding('encoding' => 'UTF8',),\cake\app\views\layouts\default.cpt⾥的charset,还有thtml的编码全部保持⼀致就⾏了。
使用_CakePHP_快速打造_Web_站点
第1 部分: 入门CakePHP 是一种用PHP 构建Web 站点的辅助工具,它很稳定,可直接用于生产及快速开发。
“使用CakePHP 快速打造Web 站点” 系列教程向您展示如何使用CakePHP 构建在线产品目录。
第 1 部分主要介绍如何安装并运行CakePHP,以及如何构建一个简单的应用程序,以允许用户注册帐户并登录到应用程序。
开始之前编者注:本系列最初发表于2006 年,并且在2007 年和2008 年进行了更新。
自从本系列上一次发表以来,CakePHP 开发人员对CakePHP 进行修改是导致对多次修订本系列的原因。
这次是针对CakePHP V1.2.2.8120 而修订的。
“使用CakePHP 快速打造Web 站点” 系列教程适合希望开始使用CakePHP 轻松构建应用程序的PHP 应用程序开发人员学习。
通过本系列教程,您将了解如何安装和配置CakePHP 以及有关Model-View-Controller(MVC)设计、如何在CakePHP 中检验用户数据、如何使用CakePHP helper、如何使用CakePHP 快速建立并运行应用程序的基本知识。
听起来好像有很多东西要学习,但不必担心— CakePHP 会替您完成其中的大部分工作。
关于本系列•第1 部分主要介绍如何安装并运行CakePHP,以及如何组成一个简单的应用程序,以允许用户注册帐户并登录到应用程序。
•第2 部分演示如何使用Scaffolding 和Bake 立即开始应用程序的开发,以及如何使用CakePHP 的访问控制列表(ACL)。
•使用CakePHP 快速打造Web 站点,第3 部分: 使用Sanitize 进行保护展示如何使用Sanitize(一个便利的CakePHP 类),通过清理用户提交的数据帮助确保应用程序的安全性。
第 3 部分还介绍CakePHP 安全组件、处理无效请求和其他高级请求验证。
•第4 部分主要介绍CakePHP 的Session 组件,演示三种保存会话数据的方法;还介绍Request Handler 组件,帮助您管理各种请求(移动浏览器、包含XML 或HTML 的请求等等)。
CAKEPHP官方说明文档资料翻译后中文版cakePHP之Request和Response对象
Request和Response对象在CakePHP2.0中的一个新功能是请求和响应对象。
在以前的版本中,这些对象通过阵列来表现,其相关方法传至RequestHandlerComponent,router,dispatcher和controller。
请求中包含的信息并没有授权的对象。
在2.0中,CakeRequest和CakeResponse用于此目的。
CakeRequestCakeRequest是CakePHP使用的默认请求对象。
它集中了多项功能,询问和请求数据交互。
对每个请求,一个CakeRequest被创建,就会被请求数据的应用程序各个层访问。
默认情况下,CakeRequest被指定到$this->request,并在controller中可用。
您还可以通过使用controller的提示在组件中使用。
CakeRequest执行的一些职能包括:•处理GET,POST,和FILES阵列到你熟悉的数据结构。
•提供有关请求的供环境自我检测。
像HEADER的发送,客户端的IP地址,运行应用程序的服务器上有关的子域/域信息。
•提供访问数组索引和对象属性的请求参数。
访问请求参数CakeRequest会公开来访问请求参数的一些接口。
首先是作为数组的索引,第二个是通过$this->request->params,第三是作为对象的属性:<?php$this->request['controller'];$this->request->controller;$this->request->params['controller']以上所有都将访问相同的值。
对已有应用,有多种访问参数的方式来灵活变动。
所有的ROUTE ELEMETNS都通过这个接口访问。
除了Route elements之外,你也经常需要访问Passed arguments和Named parameters.。
cakephp框架简介
cakephp框架The CakePHP Framework: Your First BiteBy Fabio CevascoAccording to a recent study, PHP is one of the most popular programming languages in the world. In spite of this, PHP is often criticized for its inconsistent naming conventions, its lack of important features as compared to other languages (like namespaces) and its inherent disorganization. Furthermore, PHP is very easy to learn, and this has often led to the common misconception that most PHP developers are inexperienced and that their code is therefore prone to security vulnerabilities and exploits.最近的研究表明,PHP是世界上最流行的编程语言之一。
先不说这些,PHP经常因为它矛盾的命名规则和缺少其他语言所具有的重要特性(比如命名空间),以及本身固有的不合理而受到指责。
但是PHP相当容易学习,这经常引入一个误区:PHP程序员缺少经验因此他们写的代码更容易出现安全漏洞。
This is all true, to a certain extent. PHP itself offers virtually no real structure or organization, and thereby leaves coders free to express themselves in the most unpredictable and dangerous ways: programming logic mixed with presentation elements, disorganized inclusion of other source files anywhere in a script, unnecessary and often forgotten database connections, and so on. These are obvious and common mistakes that can make PHP code completely unmaintainable.在一定程度上可以这么说。
CakePHP应用开发:第五章 模型——存取数据(10.数据的删除)
CakePHP应用开发:第五章模型——存取数据(10.数据的删除)我们已经学习了如何使用CakePHP模型的方法进行一些基本的数据库操作,像创建,读取,更新。
现在,该了解最后一种数据库操作了,那就是删除操作。
CakePHP提供两种内置的模型函数来执行删除操作。
其中一个是删除单条记录,另外一个删除多条记录。
我们接下来看一个使用模型函数del()来删除单个记录的例子。
删除单条记录使用CakePHP在数据库表中删除一条记录非常简单。
CakePHP模型默认继承的有一个专门服务此目的的方法(method),我们接下来会看到我们如何使用这模型方法来删除我们books表中的记录动手时间:删除单个记录1,在BooksController中(/app/controllers/books_controller.php)添加一个新的操作delete ():<?phpclass BooksController extends AppController{var$name='Books';var$helpers=array('Form');function index(){$books=$this->Book->find('all',array('fields'=>array('Book.id','Book.isbn','Book.title','Book.author_name'),'order'=>'Book.title ASC'));$this->set('books',$books);}function add(){if(!empty($this->data)){$this->Book->create();if(!!$this->Book->save($this->data)){$this->Session->setFlash('Book is Saved!',true);$this->redirect(array('action'=>'index'));}}}function edit($id=null){if(!$id&&empty($this->data)){$this->Session->setFlash('Invalid Book',true);$this->redirect(array('action'=>'index'));}if(!empty($this->data)){$this->Book->create();if(!!$this->Book->save($this->data)){$this->Session->setFlash('Book Updated!',true);$this->redirect(array('action'=>'index'),null,true);}}if(empty($this->data)){$this->data=$this->Book->read(null,$id);}}function delete($id=null){if(!$id){$this->Session->setFlash('Invalid Book',true);}else if($this->Book->del($id)){$this->Session->setFlash('Book is deleted',true);}else{$this->Session->setFlash('Could not delete Book',true);}$this->redirect(array('action'=>'index'));}}?>。
CakePHP使用小技巧
CakePHP使用小技巧知道主键 ID 更新一条数据,代码示例:$this->Order->id = $id;$this->Order->saveField('status', $status);点赞的时候需要+1,如何更新数据库?$this->Widget->updateAll(array('Widget.numberfield' => 'Widget.numberfield + 1'),array('Widget.id' => 1));如何通过主键最简单的方式获取到一条数据?// 只获取name字段信息$this->User->read('name', $id);// 获取所有信息$this->User->read(null, $id);CakePHP控制器如何返回上一页?$this->redirect($this->referer());CakePHP A控制器调用B控制器?$this->requestAction(array('controller'=>'Wx','action'=>'aa' ),array('data'=>array('xing'=>'A1','ming'=>'A2')));这样可以在A控制器调用B控制器方法,而且在后面传参过去,用$this->request->data获取参数值。
输出单个页面执行的 SQL 语句$log = $this->Model->getDataSource()->getLog(false, false);debug($log);Model要改一下名字才能用。
cakephp-find全解
CAKEPHP FIND书写复杂的条件语句$constraints(约束)参数中最简单的conditions(条件)键有如下结构:'conditions' => array("模型名称.字段名称" =>"比较运算符值")这个结构的好处就是我们可以使用二元运算符对它进行扩展,以便让其支持多个条件。
接下来让我们会快速通过几个例子来学习不同状况下'conditions'键的使用方法。
我们也将通过这些例子弄清楚如何通过使用字段间不同的二元操作符来实现多条件查询:1,如果我们想找一个ISBN书号为'1234567890'的书,我们只需执行如下SQL命令:SELECT * FROM `books` AS `Book` WHERE `Book`.`isbn` = '1234567890';但是在CakePHP的在BooksController中,我们可以像下面这样调用find()方法:$this->Book->find('first', array('conditions' => array('Book.isbn' => '= 1234567890')));这里使用的”=”(等于)运算符可以去掉。
CakePHP在没有找到比较运算符时会默认使用“=“运算符2,如果我们想查找书名中包含有“CakePHP”一词的书,我们可以执行如下SQL代码:SELECT * FROM `books` AS `Book` WHERE `Book`.`title` LIKE '%CakePHP%'在CakePHP中,我们会像下面这样使用find()方法$this->Book-> find('all', array('conditions' =>array('Book.title' => "LIKE %CakePHP%")));3,如果我们想查找由'Anupom Syam' , 'Ahsanul Bari' 以及'David Barnes'等人撰写的所有书籍,我们可以使用下面这个SQL语句来实现:SELECT * FROM `books` AS `Book` WHERE Book.author_name IN ( 'Anupom Syam', 'Ahsanul Bari', 'David Barnes')在CakePHP中,我们可以像下面这样使用find()方法来实现上面SQL语句的效果$this->Book-> find('all', array('conditions' => array('Book.author_name' => array('Anupom Syam','Ahsanul Bari','David Barnes'))));我们可以通过在对应的字段名后面设置一个包含有值的数组来实现与SQL逻辑运算符IN()同等的效果。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
CakePHP应用开发:第五章 模型——数据的访问(1) 模型:数据的访问 在之前的章节中,我们已经学习了MVC的基本原理,并且简单的了解了CakePHP中MVC的实现方式, 接下来 我们将单独关注MVC中的M——模型(Model)。简而言之,模型只是应用程序的数据仓库。它在应用程序和数据 库之间起到纽带作用,它包含了一款应用程序需要的所有类型的域逻辑/业务逻辑。 当今现实中的绝大多数网络应用程序都是数据密集型的。在这个时代,以一种智能的方式处理数据至关重 要。在一般的 PHP/MySQL应用程序中,域逻辑(domain logics)和数据库操作之间的区分非常麻烦。但是倘若 有了CakePHP,我们完全就不用理会这个问题。CakePHP通过模型为这个复杂的问题提供了一个简单而智能的解 决方案。 理论上,CakePHP模型是流行的设计模式—— ActiveRecord在PHP中的一个实现。它不仅仅只是一个数据库 抽象层。它帮助我们将域逻辑与应用程序和显示逻辑区分开来。此外,它也提供实用的功能让开发者不用写SQL 语句就能执行数据库操作。在CakePHP中,模型通常只是用来表示数据库中某个表的PHP类。对一个表进行的所 有数据库操作都是通过对应的模型类来完成的。每个CakePHP模型类都会默认继承数据库基本操作的一些实用函 数方法。我们也可以往包含有特定应用逻辑的模型中添加一些我们自己常用的函数方法。 模型是CakePHP框架至关重要的一部分。因此,学习如何恰当的使用模型非常重要。在这一章节,我们将彻 底认识模型的一些基本原理。具体说,来我们会看到如下内容。 如何按照CakePHP的命名规则设计一个数据库 如何为数据库中的表创建一个模型。 如何使用脚手架功能(scaffolding )来测试我们的模型。 如何使用模型的函数来轻松的完成一些常见的数据库操作任务,像数据调取,保存,和删除。 在将数据保存进数据库之前,如何对数据进行验证。