doudao9915 2012-11-09 13:20
浏览 17
已采纳

将数据连接传递给PHP类/方法的推荐方法?

As of right now I have a database connection string included at the top of each of my pages. I'm then passing my database connection to the methods in my class like this:

public function select($db) {
  //Code here
}

Code on page:

$login_user->select($db);

My thought is that if I ever want to query a different database I can just create a new connection string in my include file called $db2 and then I just pass that value instead of $db.

Is this a standard way of doing this or do you have a different recommendation?

  • 写回答

3条回答 默认 最新

  • dougu9895 2012-11-09 14:05
    关注

    Passing a connection string to your classes has lots of disadvantages and no benefits. You are on the right track, but you want to pass the database object instead of a connection string.

    Dependency Injection is a good way of giving your classes access to the database, which simply means to pass dependencies (ie database object) to the objects that need them, rather than the object itself obtaining the dependency from a global variable of some kind.

    I would suggest that you use a method like setDb() on your classes to pass the database objects, and then store it as a property for any internal use.

    For example, assuming you have created the database object $db in an initialisation script:

    class SomeClass
    {
        protected $db;
    
        public function setDb($db)
        {
            $this->db = $db;
        }
    
        public function something()
        {
            // do some query on the database using $this->db
        }
    }
    
    $obj = new SomeClass();
    $obj->setDb($db);
    
    $obj->something();
    

    DI gives you the benefits that you mentioned: the ability to easily switch the db without having to do lots of work in your methods. There are other benefits, namely ease of testing.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?