自定义MVC框架之工具类-模型类
截止目前已经改造了5个类:
这个模型类支持以下功能:
>连贯操作,js叫链式操作,连贯操作的函数可以打乱顺序,最后一个函数必须是执行语句的那个函数,如select, delete, update, add等
如 $db->table( 'user' )->where( 'id=1' )->select()
等等
->支持扩展各种子类模型,命名如: UserModel, 也可以用其他方式的,跟表名称不同的Model命名,如MyUserModel等
<?php
class Model {
protected $dbHost; //主机
protected $dbUser; //用户名
protected $dbPwd; //密码
protected $dbName; //数据库名
protected $prefix; //表前缀
protected $tbName; //表名称
protected $charset; //字符集
protected $link; //数据库连接资源
protected $sql; //拼接的sql语句
protected $options; //sql查询条件
public function __construct( $config ){
$this->dbHost = $config['db_host'];
$this->dbUser = $config['db_user'];
$this->dbPwd = $config['db_pwd'];
$this->dbName = $config['db_name'];
$this->prefix = $config['prefix'];
$this->charset = $config['charset'];
$this->link = $this->connect();
$this->tbName = $this->getTableName();
$this->initOptions();
}
protected function initOptions(){
$sqlKey = [ 'where', 'group', 'having', 'limit', 'order', 'field', 'table' ];
foreach ( $sqlKey as $key => $value ) {
$this->options[$value] = '';
if( $value == 'table' ) {
$this->options[$value] = $this->tbName;
}
}
}
public function table( $tbName ) {
if( !empty( $tbName ) ) {
$this->options['table'] = $tbName;
}
return $this;
}
public function limit( $limit ){
if( !empty( $limit ) ) {
if( is_string( $limit ) ) {
$this->options['limit'] = 'limit ' . $limit;
}else if ( is_array( $limit ) ) {
$this->options['limit'] = 'limit ' . join( ',', $limit );
}
}
return $this;
}
public function order( $order ){
if( !empty( $order ) ) {
$this->options['order'] = 'order by ' . $order;
}
return $this;
}
public function having( $having ){
if( !empty( $group ) ) {
$this->options['having'] = 'having ' . $having;
}
return $this;
}
public function group( $group ){
if( !empty( $group ) ) {
$this->options['group'] = 'group by ' . $group;
}
return $this;
}
public function where( $where ){
if( !empty( $where ) ) {
$this->options['where'] = 'where ' . $where;
}
return $this;
}
public function field( $fields ){
if( !empty( $fields ) ) {
if( is_string( $fields ) ) {
$this->options['field'] = $fields;
}else if( is_array( $fields ) ){
$this->options['field'] = join( ',', $fields );
}
}
return $this;
}
public function getTableName(){
if( !empty( $this->tbName ) ) {
return $this->prefix . $this->tbName;
}
$className = get_class( $this );
//UserModel GoodsModel, 获取Model前面的字符串(就是表名称)
$tbName = strtolower( substr( $className, , - ) );
return $this->prefix . $this->tbName;
}
protected function connect(){
$link = mysql_connect( $this->dbHost, $this->dbUser, $this->dbPwd );
if( !$link ){
die( "mysql数据库连接失败:" . mysql_error() );
}
mysql_select_db( $this->dbName, $link );
mysql_query( $this->charset );
return $link;
}
public function select(){
$sql = 'SELECT %FIELD% FROM %TABLE% %WHERE% %GROUP% %HAVING% %ORDER% %LIMIT%';
$sql = str_replace(
['%FIELD%', '%TABLE%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%'],
[ $this->options['field'], $this->options['table'], $this->options['where'], $this->options['group'], $this->options['having'], $this->options['order'], $this->options['limit'] ],
$sql
);
$this->sql = $sql;
return $this->query( $sql );
}
public function __get( $key ){
if( $key == 'sql' ) {
return $this->sql;
}else if( $key == 'prefix' ) {
return $this->prefix;
}
return false;
}
public function query( $sql ){
//执行语句之前,清空原来的options保存的sql语句临时拼接数据
$this->initOptions();
$res = mysql_query( $sql );
$data = array();
if( $res && mysql_num_rows( $res ) ) {
while( $row = mysql_fetch_assoc( $res ) ){
$data[] = $row;
}
}
return $data;
}
public function add( $data ){
$data = $this->parse( $data );
$keys = array_keys( $data );
$values = array_values( $data );
$sql = 'INSERT INTO %TABLE%(%FIELD%) values(%VALUES%)';
$sql = str_replace(
[ '%TABLE%', '%FIELD%', '%VALUES%' ],
[ $this->options['table'], join( ',', $keys ), join( ',', $values ) ],
$sql
);
$this->sql = $sql;
return $this->exec( $sql, true );
}
public function delete(){
$sql = 'DELETE FROM %TABLE% %WHERE%';
$sql = str_replace(
[ '%TABLE%', '%WHERE%' ],
[ $this->options['table'], $this->options['where'] ],
$sql
);
$this->sql = $sql;
return $this->exec( $sql );
}
public function exec( $sql, $isInsert = false ){
$this->initOptions();
$res = mysql_query( $sql );
if( $res !== false ) {
if( $isInsert ) {
return mysql_insert_id();
}else {
return mysql_affected_rows();
}
}
return false;
}
public function parse( $data ) {
$res = [];
foreach( $data as $k => $v ){
if( is_string( $v ) ) {
$res[$k] = '"' . $v . '"';
}
}
return $res;
}
public function update( $data ) {
$data = $this->parse( $data );
$fieldValue = $this->format( $data );
$sql = 'UPDATE %TABLE% SET %FIELD% %WHERE%';
$sql = str_replace(
[ '%TABLE%', '%FIELD%', '%WHERE%' ],
[ $this->options['table'], $fieldValue, $this->options['where'] ],
$sql
);
$this->sql = $sql;
return $this->exec( $sql );
}
//update ghostwu_user set field = value, where ....
protected function format( $data ){
$res = [];
foreach( $data as $k => $v ) {
$res[] = $k . '=' . $v;
}
return join( ',', $res );
}
public function __destruct(){
mysql_close( $this->link );
}
public function __call( $funcName, $args ) {
$str = substr( $funcName, , );
$field = substr( $funcName, );
if( $str == 'getBy' ) {
echo $args[];
return $this->where( $field . '="' . $args[] . '"' )->select();
}
return false;
}
}
$config = [
'db_host' => 'localhost',
'db_user' => 'root',
'db_pwd' => '',
'prefix' => 'ghostwu_',
'db_name' => 'blog',
'charset' => 'utf8',
];
$db = new Model( $config );
print_r( $db->field( '*' )->table( $db->prefix . 'users' )->getByName( 'zhangsan' ) );
echo $db->sql . PHP_EOL;
//$db->table( $db->prefix . 'users' )->where( 'id=1' )->update( [ 'name' => 'david', 'email' => 'david@gmail.com' ] );
//echo $db->sql . PHP_EOL;
//$db->table( $db->prefix . 'users' )->where( 'id in( 4, 5, 6, 7 )' )->delete();
//echo $db->sql . PHP_EOL;
//$db->table( $db->prefix . 'users' )->add( ['name' => 'zhangsan', 'email' => 'test@test.com'] );
/*
$list = $db->table( $db->prefix . 'users' )->field( [ 'name', 'email' ] )->where( 'id >= 1' )->order( 'id desc' )->limit( [0, 5] )->select();
echo $db->sql . PHP_EOL;
print_r( $list );
*/
?>
自定义MVC框架之工具类-模型类的更多相关文章
- 自定义MVC框架之工具类-图像处理类
截止目前已经改造了4个类: ubuntu:通过封装验证码类库一步步安装php的gd扩展 自定义MVC框架之工具类-分页类的封装 自定义MVC框架之工具类-文件上传类 图像处理类: 1,图片加水印处理( ...
- 自定义MVC框架之工具类-文件上传类
截止目前已经改造了3个类: ubuntu:通过封装验证码类库一步步安装php的gd扩展 自定义MVC框架之工具类-分页类的封装 该文件上传类功能如下: 1,允许定制上传的文件类型,文件mime信息,文 ...
- 自定义MVC框架之工具类-分页类的封装
以前写过一个MVC框架,封装的有点low,经过一段时间的沉淀,打算重新改造下,之前这篇文章封装过一个验证码类. 这次重新改造MVC有几个很大的收获 >全部代码都是用Ubuntu+Vim编写,以前 ...
- Java Web自定义MVC框架详解 (转)
转自:http://blog.csdn.net/jackfrued/article/details/42774459 最近给学生讲Java Web,希望他们能够在学完这部分内容后自己实现一个MVC框架 ...
- 自定义MVC框架
我们在学习自定义MVC框架的时候常常会听到Model1 ,Model2和MVC.那么什么是Model1 什么是Model2什么又是MVC呢? 什么是Model1? Model1就是一种纯jsp开发技术 ...
- Struts2 自定义MVC框架
一.Model1与Model2: Model1:就是一种纯jsp开发技术,将业务逻辑代码和视图渲染代码杂糅在一起. Model2:Model2是在Model1的基础上,将业务逻辑的代码分离开来,单独形 ...
- 第一章 自定义MVC框架
第一章 自定义MVC框架1.1 MVC模式设计 组成:Model:模型,用于数据和业务的处理 View :视图,用于数据的显示 Controller:控制器 ...
- c#自定义ORM框架---(泛型&反射&实体类扩展属性<附带通用增、删、查、改>)
该教材主要是运用到泛型.反射和实体类扩展属性 步骤一.建立扩展属性类 实体类扩展属性要继承Attribute基类完成 [AttributeUsage(AttributeTargets.Property ...
- 潭州课堂25班:Ph201805201 django框架 第六课 模型类增删改查,常用 的查询矣查询条件 (课堂笔记)
在视图函数中写入增删改查的方法 增: 在 urls 中配置路径 : 查: 1: 在后台打印数据 在模型类中添加格式化输出 : QuerySet,反回的是个对象,可以按索引聚会,用 for 循环,, 找 ...
随机推荐
- 【bug】VUE:Cannot read property '_withTask' of undefined
如题 成因:极大可能是template上有某个函数,没有在 methods中声明导致的. 解决:找到那个未声明的函数名,写在methods中.你可以使用二分法快速找到.
- 【hyperscan】编译hyperscan 4.0.0
ref: http://01org.github.io/hyperscan/dev-reference/getting_started.html 1. 硬件需求 intel x86处理器 64-bit ...
- ASP.NET Core WebApi 项目部署到 IIS 服务器的总结
Point: - ASP.NET Core WebApi 项目 - 发布到 IIS 服务器 1. 选择 File System 2. 输入要发布到的路径 # 其它默认,直接发布 3. 打开 IIS,添 ...
- 解决 ORA-27102: out of memory
记一次故障处理总结: 操作系统:windows server 2008 R2数据库版本:11.2.0.2 故障描述:外部应用连接数据库,提示连接不正常: 排错过程:1.首先 检查数据库监听服务状态是否 ...
- Centos6.7配置Nginx+Tomcat简单整合
系统环境:Centos 6.7 软件环境:JDK-1.8.0_65.Nginx-1.10.3.Tomcat-8.5.8 文档环境:/opt/app/ 存放软件目录,至于mkdir创建文件就不用再说了 ...
- JVM中OutOFMemory和StackOverflowError异常代码
1.Out of Memory 异常 右键Run As --->Run Configuration 设置JVM参数 -Xms20m -Xmx20m 上代码: /** * VM Args:-Xms ...
- 线程同步辅助类CyclicBarrier
CyclicBarrier 是一个可重置的多路同步点,在某些并行编程风格中很有用. 集合点同步:CyclicBarrier 多条线程同时执行一个阶段性任务时,相互等待,等到最后一个线程执行完阶段后,才 ...
- C++ 操作符、局部 全局变量及自动转换原则
1.&:表示与操作,eg:2&1=2&&:表示and操作,eg:1&&0=0|:表示或操作,eg:2|1=3||:表示or操作,eg:1||0=12.全 ...
- 使用控制台程序搭建WebApi
原文参考: ASP.NET Web Api 2.2: Create a Self-Hosted OWIN-Based Web Api from Scratch 新建控制台程序,引入Owin包 PM&g ...
- CentOS命令行连接带密码的wifi
安装工具包 yum install -y wpa_supplicant 确定我们要连接的wifi的名称和密码,名称为ESSID.这里假设wifi名称为TPLINK,假设密码为password,下面请注 ...