duan246558 2013-01-03 12:05
浏览 25
已采纳

PHP为什么在构造中启动数据库连接不好? [关闭]

I was reading a blog post when I came across this code:

<?php
include_once 'config.php';
class User
{
//Database connect 
public function __construct() 
{
$db = new DB_Class();
}

In the comments someone posted the following:

NEVER INITIATE db connection in the constructor

But as with all comment warriors they never give a reason why? Why is this wrong or a bad practice to do?

  • 写回答

4条回答 默认 最新

  • dongyi6269 2013-01-03 12:09
    关注

    Constructors should not do any real work:

    Work in the constructor such as: creating/initializing collaborators, communicating with other services, and logic to set up its own state removes seams needed for testing, forcing subclasses/mocks to inherit unwanted behavior. Too much work in the constructor prevents instantiation or altering collaborators in the test.

    Instead, use Dependency Injection and pass any collaborators to the constructor. This will create code that is easier to test. When you new something in the ctor, it is much more difficult to mock/stub that with a Test Double.

    Also, by injecting collaborators, you are making it easier to swap out collaborators with different implementations, thus reducing coupling, fostering code reuse and coding towards interfaces instead of concrete implementations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么