1.数据库连接及Model模型定义使用
ThinkPHP/Conf/convention.php
数据库连接配置
shop/Common/Conf/config.php
程序代码如下:
<?php
return array(
//'配置项'=>'配置值'
/* 数据库设置 */
'DB_TYPE' => 'mysql', // 数据库类型
'DB_HOST' => 'localhost', // 服务器地址
'DB_NAME' => 'demo', // 数据库名
'DB_USER' => 'root', // 用户名
'DB_PWD' => 'root', // 密码
'DB_PORT' => '3306', // 端口
'DB_PREFIX' => 'sw_', // 数据库表前缀
'DB_PARAMS' => array(), // 数据库连接参数
'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志
'DB_FIELDS_CACHE' => true, // 启用字段缓存
'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8
);
制作Model模型
a) Model本身就是一个类文件
b) 数据库中的每个数据表都对应一个Model模型文件
因为Admin、Home都需要访问数据库,可以在Admin、Home平级下创建Model文件夹。
创建Model文件夹
shop/Model/GoodsModel.class.php(最简单的数据Model模型类)
程序代码如下:
<?php
//Goods商品数据模型Model
namespace Model;
use Think\Model;
//父类Model:ThinkPHP/Library/Think/Model.class.php
class GoodsModel extends Model{
}
实例化Model对象:shop/Admin/Controller/GoodsController.class.php
程序代码如下:
public function showlist(){
//使用数据Model模型
//实例化Model对象
//实例化的对象:object(Model\GoodsModel)
//操作的数据表为:sw_goods
$goods = new \Model\GoodsModel();
echo "<pre style='color:red'>";
var_dump($goods);
echo "</pre>";
$this->display();
}
运行http://localhost/ThinkPHP/shop/index.php/Admin/Goods/showlist
运行效果
为了方便开发调试,可以将其中调试方法在入口文件处index.php封装成一个输出调试函数。
入口文件:index.php
程序代码如下:
//输出调试函数
function show_bug($msg){
echo "<pre style='color:red'>";
var_dump($msg);
echo "</pre>";
}
shop/Admin/Controller/GoodsController.class.php
程序代码如下:
public function showlist(){
//使用数据Model模型
//实例化Model对象
//实例化的对象:object(Model\GoodsModel)
//操作的数据表为:sw_goods
$goods = new \Model\GoodsModel();
show_bug($goods);
$this->display();
}
运行http://localhost/ThinkPHP/shop/index.php/Admin/Goods/showlist
运行效果
在本案例中,输出页面显示的属性都是Model父类的默认值(继承于Model父类):ThinkPHP/Library/Think/Model.class.php
Model父类
可以给当前Model定义一些个性化设置
shop/Model/QqModel.class.php
程序代码如下:
<?php
namespace Model;
use Think\Model;
class QqModel extends Model{
//可以给当前Model定义一些个性化设置
// 实际数据表名(包含表前缀)
//protected $trueTableName = 'tencent_qq';
}