내 데이터베이스에 연결하는 정적 메서드를 클래스에 추가하고 데이터 배열을 반환하고 싶습니다. 예를 들어 Users라는 클래스와 User라는 클래스가 있는데 $ user = User :: fetch ($ id)를 호출하여 지정된 사용자의 정보 배열을 가져올 수 있어야합니다. 그래서 내 질문은 언제 어디서 데이터베이스에 연결해야합니까? 비슷한 목적으로 사용되는 정적 메서드를 호출 할 때마다 데이터베이스 연결 정보를 전달해야합니까? 그것은 단지 옳다고 생각하지 않습니다.PHP : 정적 메서드로 데이터베이스에 연결
0
A
답변
0
내가 뭘 매우 초기에 발생시키는의 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 데이터베이스 클래스를 사용하는 연결 관리자입니다. 이 실행되면 말 그대로 나를 대신 Manager::table()
의 ....... DB::table()
을 사용할 수 있습니다
use Illuminate\Database\Capsule\Manager;
/**
* Class DB
* This is a Facade of the Connection established by ConnectionManager
*
* @package INSP\Database
*/
class DB extends Manager
{
}
또 다른 외관을 가지고있다.
희망 하시겠습니까?
0
는 응용 프로그램 (__destruct
방법 또는 register_shutdown
)를 종료 할 때 당신은 당신이 연결에게 당신이 그것을 필요로 처음 확인하고 연결을 종료해야합니다
관련 문제
- 1. 데이터베이스에 PHP 연결 : 안전합니까?
- 2. 데이터베이스에 PHP 연결
- 3. 정적 메서드로 정적 변수 변경
- 4. 비 정적 메서드로 정적 메서드 덮어 쓰기
- 5. ImageView를 정적 메서드로 설정
- 6. php - 데이터베이스에 대한 다중 연결
- 7. PHP 문제가있는 mysql 데이터베이스에 연결
- 8. H2 데이터베이스에 PHP ODBC 연결
- 9. Azure-SQL 데이터베이스에 PHP 연결
- 10. 기본 PHP 질문 - 데이터베이스에 연결
- 11. C# : PHP MySQL 데이터베이스에 연결
- 12. php, xampp을 사용하여 데이터베이스에 연결
- 13. MySQL 데이터베이스에 안드로이드와 PHP 연결
- 14. SQL/PHP - PHP로 데이터베이스에 연결
- 15. 비 정적 메서드를 정적 메서드로 호출하는 방법?
- 16. 정적 메서드로 클래스 종속성을 인스턴스화하십시오.
- 17. 정적 메서드로 인스턴스 메서드 재정의
- 18. android - 정적 메서드로 인한 문제
- 19. Swift는 정적 메서드로 Self를 초기화합니다.
- 20. 체인 정적 메서드로 데이터 반환
- 21. 정적 메서드에서 정적 메서드 호출 정적 메서드로 만든 USING 인스턴스
- 22. ActionListener를 다른 클래스의 메서드로 연결
- 23. PHP, 로그인을위한 데이터베이스에 내 SQL 연결
- 24. MS Access 2016 데이터베이스에 PHP 원격 연결
- 25. sqlsrv_connect()를 통해 mssql 데이터베이스에 연결 - PHP
- 26. 데이터베이스에 연결
- 27. 데이터베이스에 연결
- 28. 데이터베이스에 연결
- 29. 데이터베이스에 연결
- 30. 데이터베이스에 연결
아니요, 매번 데이터베이스 연결 정보를 전달할 필요가 없습니다. db 연결에 싱글 톤 패턴을 사용해보십시오. –