php mvc初步分层代码

匿名 (未验证) 提交于 2019-12-02 22:11:45

MySQL.class.php 底层的sql处理 添加单例模式,只允许实例化一次

BaseModel.class.php 基本的 model 设定最mysql的基本数据 并创建了连接

↓ 是BillModel的父类

BillModel.class.php 处理bill表中相应的逻辑

BillController.class.php bill类的处理器 负责 mvc中的 c连接 m v

↓ show

index.html

具体代码:

MySQL.class.php

<?php

/*
设计一个类:mysqli数据库操作类
设计目标:
1,该类一实例化,就可以自动连接上mysqli数据库;


4,可以主动关闭连接;
*/


class MySQLDB{


private $link = null; //用于存储连接成功后的“资源”


//定义一些属性,以存储连接数据库的6项基本信息
private $host;
private $port;
private $user;
private $pass;
private $charset;
private $dbname;


//实现单例第2步:用于存储唯一的单例对象:
private static $instance = null;
//实现单例第3步:

//if( !isset( self::$instance )){ //还没有该对象
if( !(self::$instance instanceof self) ){ //这一行代替上一行的判断,更常见
self::$instance = new self($config); //就创建并存起来
}
return self::$instance;
}
//实现单例第4步:私有化这个克隆的魔术方法
private function __clone(){}


//实现单例第1步:
private function __construct($config){
//先将这些基本的连接信息,保存起来!
$this->host = !empty($config['host']) ? $config['host'] : "localhost"; //考虑空值情况,使用默认值代替
$this->port = !empty($config['port']) ? $config['port'] : "3306" ;
$this->user = !empty($config['user']) ? $config['user'] : "root" ;
$this->pass = !empty($config['pass']) ? $config['pass'] : "" ;
$this->charset = !empty($config['charset']) ? $config['charset'] : "utf8" ;
$this->dbname = !empty($config['dbname']) ? $config['dbname'] : "php39" ;

//然后连接数据库!

or die("连接失败");


//设定编码
//mysqli_query("set names {$config['charset']}");
$this->setCharset( $this->charset );//这一行代替上一行


//选定要使用的数据库名

$this->selectDB( $this->dbname );//这一行代替上一行
}
//可以设定要使用的连接编码
function setCharset( $charset ){
$this->link->query("set names $charset");
}
//可以设定要使用的数据库
function selectDB($dbname){

}
//可关闭连接
function closeDB(){
$this->link->close();
}


//这个方法为了执行一条增删改语句,它可以返回真假结果
function runQuery($sql){
$result = $this->link->query($sql);
return true; //因为是增删改语句,直接返回true就可以

}

}

BaseModel.class.php

<?php
require('MySQL.class.php');
class BaseModel{
protected $db=null;//存储数据库工具类的实例
function __construct(){
$config=array(
'host'=>"localhost",
'port'=>"3306",
'user'=>"root",
'pass'=>"root",
'charset'=>"utf8",
'dbname'=>"db_market"
);
$this->db=MySQLDB::getInstance($config);
}

}

BillModel.class.php

<?php







ModelFactory.class.php

<?php
//单例工厂类
//通过这个工厂类,可以传递过来一个模型类的类名
//并返回给类的一个实例,并且,保证其为“单例的”;













BillController.class.php

<?php






index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>成功执行了语句</h1>
程序返回值为<?php echo $count;?>
</body>
</html>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!