2013-12-16 3 views
0

내 데이터베이스에 연결하는 정적 메서드를 클래스에 추가하고 데이터 배열을 반환하고 싶습니다. 예를 들어 Users라는 클래스와 User라는 클래스가 있는데 $ user = User :: fetch ($ id)를 호출하여 지정된 사용자의 정보 배열을 가져올 수 있어야합니다. 그래서 내 질문은 언제 어디서 데이터베이스에 연결해야합니까? 비슷한 목적으로 사용되는 정적 메서드를 호출 할 때마다 데이터베이스 연결 정보를 전달해야합니까? 그것은 단지 옳다고 생각하지 않습니다.PHP : 정적 메서드로 데이터베이스에 연결

+0

아니요, 매번 데이터베이스 연결 정보를 전달할 필요가 없습니다. db 연결에 싱글 톤 패턴을 사용해보십시오. –

답변

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)를 종료 할 때 당신은 당신이 연결에게 당신이 그것을 필요로 처음 확인하고 연결을 종료해야합니다

관련 문제