I have a class that deals with a number of database operations. I want the class to be as re-usable and well-designed as possible, and I'm fairly new to OOP, so I would appreciate a solution to this:

我有一个类处理许多数据库操作。我希望这个类尽可能地重复使用并且设计得很好,而且我对OOP还是个新手,所以我很感激这个解决方案:

Is it better practice to do:

这是更好的做法:

class MyDatabase extends Database 
{
    private $connection;

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

    //More functions below

}

or

class MyDatabase extends Database 
{
    private $connection;

    public function __construct()
    {
        $this->connection=new mysqli(...);
    }

    //More functions below

}

What are the pros/cons of both, and which one is used more often? I can't really decide for myself which one I should start using, and it will affect the rest of the application I'm writing.

两者的优点/缺点是什么,哪一个更经常使用?我无法自己决定应该开始使用哪一个,这将影响我正在编写的其他应用程序。

Thank you

2 个解决方案

#1


1

I would suggest the first one, no hard coded dependency, testable and can change the connection object at anytime. I highly recommend you to watch this.

我建议第一个,没有硬编码依赖,可测试,并可以随时更改连接对象。我强烈建议你看这个。

更多相关文章

  1. 如何实现分布式文件上传解决方案?
  2. 一套PHP做app接口的解决方案
  3. curl获取网页内容出现乱码或为空的解决方案,另附curl_getinfo函数
  4. PHP - Content-type未指定假设应用程序/x-www-form-urlencode。
  5. 在php和servlet应用程序之间进行通信
  6. 使用PHP和MySQL开发“测试”Web应用程序的数据库设计
  7. PHP XAMPP配置PHP环境和Apache80端口被占用解决方案
  8. 数据库是存储我的Web应用程序数据的最佳选择吗?
  9. 架构比MVC更适合Web应用程序?

随机推荐

  1. 「Jenkins」- 使用接口批量创建任务
  2. Day-3
  3. 服务端开发指南与最佳实战 | 数据存储技
  4. AssemblyScript 入门指南[每日前端夜话0x
  5. 计算系统基础(一)
  6. 选择合适的数据存储方案
  7. 全球开发者报告:1100万开发人员积极使用 J
  8. JavaScript测试教程–part 4:模拟 API 调
  9. 服务端指南 数据存储篇 | MySQL(08) 分库与
  10. 常用数据结构的 JavaScript 实现代码[每