jasteele123

ADODB use existing PDO connection

Nov 15th, 2013
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.22 KB | None | 0 0
  1. <?php
  2. /**
  3.  * The default database handle is a PDO object.
  4.  * This will be used for normal database interaction.
  5.  */
  6. $db = new PDO('mysql:host=127.0.0.1;dbname=test', 'user', 'password');
  7.  
  8. /**
  9.  * But if I run into legacy code which needs ADOdb to do something
  10.  * I would like to use the existing PDO connection instead of wasting
  11.  * resources making a second connection to the same database.
  12.  */
  13. require_once('adodb/adodb.inc.php');
  14. require_once('adodb/drivers/adodb-pdo.inc.php');
  15.  
  16. class CustomAdodbPdo extends ADODB_pdo {
  17.     function __construct($pdo) {
  18.         try {
  19.             $this->_connectionID = $pdo;
  20.         } catch (Exception $e) {
  21.             $this->_connectionID = false;
  22.             $this->_errorno = -1;
  23.             $this->_errormsg = 'Connection attempt failed: '.$e->getMessage();
  24.             return false;
  25.         }
  26.  
  27.         if ($this->_connectionID) {
  28.             $this->dsnType = strtolower(PDO::ATTR_DRIVER_NAME);
  29.             switch (ADODB_ASSOC_CASE) {
  30.                 case 0: $m = PDO::CASE_LOWER; break;
  31.                 case 1: $m = PDO::CASE_UPPER; break;
  32.                 default:
  33.                 case 2: $m = PDO::CASE_NATURAL; break;
  34.             }
  35.             $this->_connectionID->setAttribute(PDO::ATTR_CASE,$m);
  36.             $class = 'ADODB_pdo_'.$this->dsnType;
  37.             switch ($this->dsnType) {
  38.                 case 'oci':
  39.                 case 'mysql':
  40.                 case 'pgsql':
  41.                 case 'mssql':
  42.                     include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
  43.                     break;
  44.             }
  45.             if (class_exists($class))
  46.                 $this->_driver = new $class();
  47.             else
  48.                 $this->_driver = new ADODB_pdo_base();
  49.  
  50.             $this->_driver->_connectionID = $this->_connectionID;
  51.             $this->_UpdatePDO();
  52.             return true;
  53.         }
  54.         $this->_driver = new ADODB_pdo_base();
  55.         return false;
  56.     }
  57. }
  58.  
  59. $ADODB_NEWCONNECTION = 'CustomPdoFactory';
  60. function &CustomPdoFactory() {
  61.     global $db;
  62.  
  63.     $obj = new CustomAdodbPdo($db);
  64.     return $obj;
  65. }
  66.  
  67.   // The ADONewConnection() now uses the existing PDO connection "$db"
  68. $adodb = &ADONewConnection();
  69. ?>
Advertisement
Add Comment
Please, Sign In to add comment