Home  >  Article  >  Backend Development  >  评价一上,小弟我写的oop

评价一上,小弟我写的oop

WBOY
WBOYOriginal
2016-06-13 11:08:231060browse

评价一下,我写的oop
谢谢了,就是一个连数据库的类

class db{
public $conn;
function __construct(){
$this->conn=mysqli_connect('localhost','root','123123','air');
//$this->conn->query('SET NAMES UTF8');
mysqli_query($this->conn,'SET NAMES UTF8');
}
public function delete($table,$condition=""){
if(empty($condition)) {
$this->halt('没有设置删除的条件');
return false;
}
$sql = "delete from ".$table." where 1=1 and ".$condition;
if(!$this->conn->query($sql)){
return false;
}else{
return true;
}//if
}
public function getAll($sql){//输出数组所有
$rt=array();
$q=$this->conn->query($sql);
$this->conn->query('SET NAMES UTF8');
while($r=$q->fetch_array(MYSQLI_USE_RESULT)){
$rt[]=$r;
}
return $rt;
}
public function __destruct(){
mysqli_close($this->conn);
}
}//db
?>

------解决方案--------------------
感觉连接数据库不应该和数据访问层卸载一起吧,那样如果你要是访问别的数据库的话,这个类还得修改,所以还是应该单独提出来,这样后期就不用修改数据访问层了,直接改configuration就可以了。
if(!$this->conn->query($sql)){
            return false;
        }else{
             return true;
         }
这个好像也可以单独拿出来写成一个function吧。
------解决方案--------------------
第一:$conn这个连接应该修饰符为private(封装性)
第二:组织sql语句应该放在逻辑层(按照MVC设计模式)
第三:对数据库的操作的类,一般写一个dml(修改),dql(查询)两个函数。所以你的那个getAll不应该写在这个类中(我一般写代码这个类喜欢叫SqlHelper.class.php,里面写一个execute_dml函数,和一个execute_dql函数,构造函数用于连接数据库)
呵呵!!!我也是刚刚学PHP,菜鸟一个。以上只是我个人见解,不知道对还是不对。。。
------解决方案--------------------
首先呢, 这个OO的设计, 没法绝对地说这个好还是那样好, 一个类提供的接口应该是根据需求决定的, 如何划分类的功能也是根据需求来决定, 所以别人也没法凭空判断. 
比如说你这个类, 有insert, 有query(getAll), 没看见update, 要么是你没贴全, 但是如果你的应用目前和将来都不需要update, 那没有也没什么错. 

随便说点细节上的东西:
1. 'SET NAMES UTF8' 没必要在getAll里, 连接后运行一次即可.
2. $this->conn->query和mysqli_query混用, 统一比较好看
3. delete($table,$condition="")和getAll($sql), 接口不一致, 使用你这个类的会比较头疼
4. mysqli_connect和$this->conn->query之后都最好检查错误
.....
x. 代码没贴全: $this->halt是什么?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn