关于mysql:PHP:以静态方法连接到数据库

PHP: Connecting to a database in a static method

我想向类中添加一个静态方法,该方法连接到我的数据库并返回一个数据数组。例如,我有一个名为user s的表和一个名为user的类,我希望能够调用$user=user::fetch($id)来获取指定用户的信息数组。所以我的问题是,我应该在何时何地连接到数据库?每次调用具有类似用途的静态方法时,是否需要传递数据库连接信息?感觉不太对劲。


我要做的是有一个ConnectionManager类,它在连接到相关数据库但使用单例模式的应用程序运行时很早就启动了。所以一旦它运行一次,我就可以在整个项目中全局访问连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use Illuminate\Cache\CacheManager;
use Illuminate\Cache\MemcachedConnector;
use Illuminate\Database\Capsule\Manager as Capsule;
use INSP\Config;
use INSP\Core;
use INSP\Di;

/**
 * Class ConnectionManager
 *
 * @package INSP\Database
 */

class ConnectionManager
{

    /**
     * @var \Illuminate\Database\Connection
     */

    protected static $instance;

    /**
     * Loads database configuration from static file if it exists if not it loads from
     * Wordpress defaults
     *
     * @param bool $config
     */

    public function __construct($config = false)
    {
        /*
         * If config is not provided in the constructor check for a config file in the
         * config directory, if that doesn't exist use the database config from wp_config
         */

        if (!$config && file_exists(Core::baseDir() . '/Config/database.php')) {
            $config = include(Core::baseDir() . '/Config/database.php');
        } else {
            if (!defined('DB_HOST')) {
                if (file_exists(Core::baseDir() . '/local-config.php')) {
                    define('WP_LOCAL_DEV', true);
                    require_once(Core::baseDir() . '/local-config.php');
                } else {
                    require_once(Core::baseDir() . '/production-config.php');

                }
            }
            $config = array(
                'driver'    => 'mysql',
                'host'      => DB_HOST,
                'database'  => DB_NAME,
                'username'  => DB_USER,
                'password'  => DB_PASSWORD,
                'charset'   => DB_CHARSET,
                'collation' => 'utf8_unicode_ci',
            );
        }

        return self::connect($config);

    }

    /**
     * This method is in charge or setting up all connection's including
     * the k2 and mocked testing connection(uTest)
     *
     * @param $config
     *
     * @return \Illuminate\Database\Connection
     */

    public static function connect($config)
    {
        $capsule = new Capsule();
        // Load some ancillary configurations
        $k2Config = Config::getAll('Apis/k2');
        $unitConfig = array(
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => ''
        );
        // Add all needed configurations to connections and name them if needed
        $capsule->addConnection($config);
        $capsule->addConnection($k2Config, 'k2');
        $capsule->addConnection($unitConfig, 'uTest');

        // Add capsule to global namespace so we can use it later
        $capsule->setAsGlobal();

        // Start the caching library so we can use the remember(ttl) method in our queries
        $container = $capsule->getContainer();

        $cacheConfig = Config::getAll('cache');
        $memcachedServers = Config::get('cache.memcached');

        $container['memcached.connector'] = new MemcachedConnector();
        $container['config']['cache.driver'] = $cacheConfig['driver'];
        $container['config']['cache.path'] = $cacheConfig['file']['directory'];
        $container['config']['cache.connection'] = null;
        $container['config']['cache.table'] = 'cache';
        $container['config']['cache.memcached'] = $memcachedServers;
        $container['config']['cache.prefix'] = $cacheConfig['prefix'];

        // If Memcached is not installed default to file storage
        if (!class_exists('Memcached', false)) {
            $container['config']['cache.driver'] = 'file';
        }

        // Start Dependency Injection if it hasn't already been started
        Di::init();
        $cacheManager = new CacheManager($container);

        Di::set('cacheManager', $cacheManager);

        $capsule->setCacheManager($cacheManager);

        return $capsule->connection();
    }

    /**
     * @param bool $config
     *
     * @return ConnectionManager
     */

    public static function init($config = false)
    {
        if (!is_object(self::$instance)) {
            self::$instance = new ConnectionManager($config);
        }
        return self::$instance;
    }

}

这是我的连接管理器,它在框架之外使用幼虫数据库类。一旦这被运行,我就有了另一个表面

1
2
3
4
5
6
7
8
9
10
11
use Illuminate\Database\Capsule\Manager;

/**
 * Class DB
 * This is a Facade of the Connection established by ConnectionManager
 *
 * @package INSP\Database
 */

class DB extends Manager
    {
    }

这让我使用DB::table()……而不是Manager::table()

希望这有帮助


您需要在第一次需要时建立连接,并在应用程序关闭时关闭连接(__destruct方法或register_shutdown)