传入连接对象或在类中创建它? (OOP)
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.
我建议第一个,没有硬编码依赖,可测试,并可以随时更改连接对象。我强烈建议你看这个。
更多相关文章
- 如何实现分布式文件上传解决方案?
- 一套PHP做app接口的解决方案
- curl获取网页内容出现乱码或为空的解决方案,另附curl_getinfo函数
- PHP - Content-type未指定假设应用程序/x-www-form-urlencode。
- 在php和servlet应用程序之间进行通信
- 使用PHP和MySQL开发“测试”Web应用程序的数据库设计
- PHP XAMPP配置PHP环境和Apache80端口被占用解决方案
- 数据库是存储我的Web应用程序数据的最佳选择吗?
- 架构比MVC更适合Web应用程序?