dongyu4863 2012-09-30 15:17
浏览 36
已采纳

在PHP中选择设计模式?

I develop web applications with PHP. I have many classes using a database connection.

This is the structure i generally use;

class SomeClass {
    private $db;

    function __construct(mysqli $db) {
        $this->db = $db;
    }

    function SomeFunction() {
        $this->db->query(...);
    }
}

And this is what i thought to use;

class Common {
    public static DB = new mysqli(...);
}

class SomeClass {
    function SomeFunction() {
        Common::DB->query(...);
    }
}

There are two parts of my question;

  1. Which one is better practice? If i use first one, i have to pass database object to every class uses db. If i use second one, every class uses db will be dependent to Common class.

  2. I made examples simpler. Actually i have a Database class extends mysqli and a DatabaseTableManager class using Database class. I add GetTable() function to Database class. I create DatabaseTableManager objects in this function (return new DatabaseTableManager($this, $tableNameFromArgument)) so i do not have to pass db object every time. In DatabaseTableManager class, i built some queries to make my job easier.

E.g. to insert a record to a table;

$DB = new Database(...);
$myTable = $DB->GetTable('myActualTableNameInDatabase');
$myTable->Insert( array('col1' => 'val1', 'col2' => 'val2') );

So i use this class a lot in my other classes. Naturally all these classes become dependent to DatabaseTableManager class. What is the better solution?

  • 写回答

3条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥20 51单片机实训实验报告
      • ¥15 C# 循环读写数据中途突然变慢
      • ¥15 用Java实现双端队列
      • ¥150 ID3决策树实现分类
      • ¥15 multisim10安装后,找不到NI License Manager的程序来安装许可证
      • ¥15 C++银行卡系统 Help!
      • ¥15 R语言数据分析的相关问题
      • ¥15 模型导入SP后贴图纹理只有一个,拆了四张UV的,怎么解决?
      • ¥15 检索带order by 非常慢
      • ¥20 python 爬虫 token 加密方式