Pimcore\Db::getConnection PHP Method

getConnection() public static method

public static getConnection ( boolean $raw = false, boolean $writeOnly = false ) : Wrapper | Zend_Db_Adapter_Abstract
$raw boolean
$writeOnly boolean
return Pimcore\Db\Wrapper | Zend_Db_Adapter_Abstract
    public static function getConnection($raw = false, $writeOnly = false)
    {
        // just return the wrapper (for compatibility reasons)
        // the wrapper itself get's then the connection using $raw = true
        if (!$raw) {
            return new Wrapper();
        }
        $charset = "utf8mb4";
        // explicit set charset for connection (to the adapter)
        $config = Config::getSystemConfig()->database->toArray();
        // write only handling
        if ($writeOnly && isset($config["writeOnly"])) {
            // overwrite params with write only configuration
            $config["params"] = $config["writeOnly"]["params"];
        } elseif ($writeOnly) {
            throw new \Exception("writeOnly connection is requested but not configured");
        }
        $config["params"]["charset"] = $charset;
        try {
            $db = \Zend_Db::factory($config["adapter"], $config["params"]);
            $db->query("SET NAMES " . $charset);
        } catch (\Exception $e) {
            Logger::emerg($e);
            \Pimcore\Tool::exitWithError("Database Error! See debug.log for details");
        }
        // try to set innodb as default storage-engine
        try {
            $db->query("SET default_storage_engine=InnoDB;");
        } catch (\Exception $e) {
            Logger::warn($e);
        }
        // try to set mysql mode
        try {
            $db->query("SET sql_mode = '';");
        } catch (\Exception $e) {
            Logger::warn($e);
        }
        $connectionId = $db->fetchOne("SELECT CONNECTION_ID()");
        // enable the db-profiler if the devmode is on and there is no custom profiler set (eg. in system.xml)
        if (PIMCORE_DEVMODE && !$db->getProfiler()->getEnabled() || array_key_exists("pimcore_log", $_REQUEST) && \Pimcore::inDebugMode()) {
            $profiler = new \Pimcore\Db\Profiler('All DB Queries');
            $profiler->setEnabled(true);
            $profiler->setConnectionId($connectionId);
            $db->setProfiler($profiler);
        }
        Logger::debug(get_class($db) . ": Successfully established connection to MySQL-Server, Process-ID: " . $connectionId);
        return $db;
    }

Usage Example

Beispiel #1
0
 /**
  * @return \Zend_Db_Adapter_Abstract
  */
 protected function getDb()
 {
     if (!$this->db) {
         // we're using a new mysql connection here to avoid problems with active (nested) transactions
         \Logger::debug("Initialize dedicated MySQL connection for the cache adapter");
         $this->db = Db::getConnection();
     }
     return $this->db;
 }
All Usage Examples Of Pimcore\Db::getConnection