gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:55:16 25 4
gpt4 key购买 nike

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

最佳答案

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

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;
}

}

这是我的连接管理器,它在框架之外使用larvels数据库类。一旦运行,我就有了另一个外观,实际上是

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()

希望这有帮助

关于PHP:以静态方法连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20617841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com