组织PHP OOP类以与DB一起使用 [英] organizing PHP OOP classes to work with DB

查看:109
本文介绍了组织PHP OOP类以与DB一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个PHP项目,有非常奇怪的类结构。像这样:

Today I have a PHP-project with very strange class structure. Like this:

db_base
  `-- db_base_ext extends db_base
        +-- module_1 extends db_base_ext
        +-- module_2 extends db_base_ext
        .   ...
        +-- module_N extends db_base_ext
        `-- db_user extends db_base_ext

class_1
  `-- submodule_1_1 extends class_1

db_base 连接到 code>并有一些帮助方法。

db_base connects to db in __construct() and have some helper methods.

执行示例:

$db = new db_user();
$user = new user($db);
unset($db);

$db = new module_2();

我不喜欢这个代码我们连接到DB两次,整个类结构不是非常好。

I don't like that in this code we connects to DB twice and the whole class structure is not really good.

如何使它更好?我的意思是只创建一个数据库实例,之后用任何类(对应于DB)工作?

How can I make it better? I mean create only one DB instance and after this work with any class (corresponding to DB)?

单例模式对此有好处吗?

Will singleton pattern be good for this?

推荐答案

您的问题在于您的结构,

Your problem here is that, your structures,

module_2 extends db_base_ext
db_user extends db_base_ext
submodule_1_1 extends class_1

打破单一责任原则 Liskov替换原则


如何做得更好。我的意思是只创建一个数据库实例,在
之后可以使用任何类(对应于DB)。

How can I make it better. I mean create only one DB instance and after this work with any class (corresponding to DB), is possible?

依赖注入是要走的路。您将实例化一个数据库实例,所有类将共享相同 $ db 实例。

Dependency injection is the way to go. You would instantiate one db instance and all your classes would share the same $db instance.

final class MySQLPDO extends PDO
{
    public function __construct(array $params)
    {
      parent::__construct(sprintf('mysql: host=%s; dbname=%s', $params['host'], $params['database']), $params['username'], $params['password']);

      $this->setAttribute(parent::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES UTF8');
      $this->setAttribute(parent::ATTR_ERRMODE, parent::ERRMODE_EXCEPTION);
      $this->setAttribute(parent::ATTR_EMULATE_PREPARES, false);
      $this->setAttribute(parent::ATTR_DEFAULT_FETCH_MODE, parent::FETCH_ASSOC);

    }
}

$db = new MySQLPDO(array(
     'host'     => 'localhost',
     'database' => 'foo',
     'username' => 'root',
     'password' => '',
));
$user = new User($db);

$module = new Module1($user);
$foo = new Foo($db);

那么,你在这里会得到什么?

So, what would you gain here? Both reuse-ability and test-ability.

注意,你应该避免Singleton的引入另一种形式的全局状态,这对于单元测试目的是不利的。

Note, you should avoid Singleton's as they introduce another form of global state, which is bad for unit-testing purposes.

这篇关于组织PHP OOP类以与DB一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆