PHP:以静态方法连接到数据库[关闭](PHP: Connecting to a database in a static method [closed])

编程入门 行业动态 更新时间:2024-10-27 22:21:14
PHP:以静态方法连接到数据库[关闭](PHP: Connecting to a database in a static method [closed])

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

I want to add a static method to my class that connects to my database and returns an array of data. E.g., I have a table called Users and a class called User, and I want to be able to call $user = User::fetch($id) to get an array of the specified user's information. So my question is, when and where should I connect to the database? Do I need to pass the database connection information every time I call static methods that serve a similar purpose? That just doesn't feel right.

最满意答案

我所做的是有一个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() 。

希望这可以帮助

What i do is have a ConnectionManager class that fires very early in the applications runtime that connects to the relevant database(s) but is using a singleton pattern. So once it's ran once i can access the connection globally throughout the project.

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

This is my connection manager that uses larvels database classes outside of the framework. once this is ran i have another Facade that is literally

use Illuminate\Database\Capsule\Manager; /** * Class DB * This is a Facade of the Connection established by ConnectionManager * * @package INSP\Database */ class DB extends Manager { }

Which lets me use DB::table()....... instead of Manager::table().

Hope this helps

更多推荐

本文发布于:2023-07-14 20:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   静态   数据库   方法   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!