dtrgqjcd877528 2011-10-18 09:37
浏览 18
已采纳

PHP - 改进我的数据库模型?

I am administering a system which is fairly old. It is a code soup at the moment and bit by bit I have been refactoring the code.

Something I noticed while doing this was that 90% of the queries were CRUD. No joins, nothing else. All really simple stuff.

As a result I created a model class which cover's these types of query's. I then extend the model class for each table.

class Model extends MySQLi {
    public function __construct() {
        global $site;
        $mysql = $site['mysql'];
        parent::__construct($mysql['host'], $mysql['user'], $mysql['pass'], $mysql['db']);
    }

I don't like the use of the global but it does allow me to do this without having to worry about connection details.

<?php
class Contact extends Model {

    public $table = 'contact';

}

$Contact = new Contact;
$Contact->get(array('where'=>array('id >' => 4), 'limit' => array(0, 20));

My concern is that if a script requires 3 tables. I will be using 3 models and thus surely that means I will have 3 independent database connections? One for each class?

Is this going to be a problem like I think it will be?

Is there a work around which will allow me to continue to extend MySQLi and maybe pass it an active connection instead of connection details for it to make its own connection?

  • 写回答

1条回答 默认 最新

  • dougu2006 2011-10-18 09:43
    关注

    Do not extend Mysqli, just contain it in your model.

    class Model {
        protected $db;
    
        public function __construct($db) {
            $this->db = $db;   // the mysqli instance.
        }
        .....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置