什么是获取数据库连接/对象到PHP中的函数的最好的方法? [英] What is the best method for getting a database connection/object into a function in PHP?

查看:106
本文介绍了什么是获取数据库连接/对象到PHP中的函数的最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个选项是:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) { ... }

function UsingGlobal() {
    global $connection;
    ...
}



因此,传入,或使用全局。我想在功能,只使用在1个项目,将只有1个数据库连接。如果有多个连接,绝对通过引用传递或传递。

So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.

当你在PHP5使用对象时,我不需要通过引用传递,所以然后传入或使用全局是两种可能。

I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.

我问的原因是因为我厌倦了总是把$连接放入我的函数参数。

The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.

推荐答案

我使用Singleton ResourceManager类通过整个应用程序处理像DB连接和配置设置这样的东西:

I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:

class ResourceManager {
    private static $DB;
    private static $Config;

    public static function get($resource, $options = false) {
        if (property_exists('ResourceManager', $resource)) {
            if (empty(self::$$resource)) {
                self::_init_resource($resource, $options);
            }
            if (!empty(self::$$resource)) {
                return self::$$resource;
            }
        }
        return null;
    }

    private static function _init_resource($resource, $options = null) {
        if ($resource == 'DB') {
            $dsn = 'mysql:host=localhost';
            $username = 'my_username';
            $password = 'p4ssw0rd';
            try {
                self::$DB = new PDO($dsn, $username, $password);
            } catch (PDOException $e) {
                echo 'Connection failed: ' . $e->getMessage();
            }
        } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
            self::$$resource = new $resource($options);
        }
    }
}

/ where ever:

And then in functions / objects / where ever:

function doDBThingy() {
    $db = ResourceManager::get('DB');
    if ($db) {
        $stmt = $db->prepare('SELECT * FROM `table`');
        etc...
    }
}

以存储消息,错误消息和警告以及全局变量。有一个有趣的问题这里何时实际使用此类型的类。

I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question here on when to actually use this type of class.

这篇关于什么是获取数据库连接/对象到PHP中的函数的最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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