将数据连接传递给PHP类/方法的推荐方法? [英] Recommended way for passing data connection to a PHP class / method?

查看:96
本文介绍了将数据连接传递给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
}

页面上的代码

$login_user->select($db);

我的想法是,如果我想查询其他数据库,我可以在包含文件$ db2中创建一个新的连接字符串,然后直接传递该值而不是$ 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?

推荐答案

将连接字符串传递给您的类有很多弊端,没有好处.您走在正确的道路上,但是您希望传递数据库对象而不是连接字符串.

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.

我建议您在类上使用类似setDb()的方法来传递数据库对象,然后将其存储为属性以供内部使用.

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.

例如,假设您已在初始化脚本中创建了数据库对象$db:

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给您带来了您提到的好处:能够轻松切换数据库而无需在方法中进行大量工作的能力.还有其他好处,就是易于测试.

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.

这篇关于将数据连接传递给PHP类/方法的推荐方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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