...

View Full Version : Resolved Pass a connection over to another method



Oatley
11-13-2012, 04:17 PM
Hello, I'm having trouble passing a connection in one method over to another method called doQuery. I can successfully connect to the database, but cant seem to run a query as I am unsure how I pass over my connection to the doQuery method.




class PDO {

public static function getConnection() {
if(!isset(self::$instance)) {
try {
self::$instance = new PDO(xxxxxx);
self::$instance->setAttribute(xxxxxxxx);
self::$instance = new static();
} catch (PDOException $e){
throw new Exception('Sorry, we could not connect you to the database for some reason');
}
}
return self::$instance;
}

public function doQuery($table) {
$db = self::getConnection(); //Grab the connection ->Does not seem to work
$Q = $db->prepare("SELECT * from $table LIMIT 1");
$Q->execute();
$RES = $QUERY->fetch();
print_r($RES);
}

}


Testing



$Q = Connection::getConnection('PDO');
$Q->doQuery('tablename');


Would anyone be able to help please?

Thank You

Fou-Lu
11-13-2012, 04:57 PM
You don't have a queryable type (well you sorta do). Don't call your class PDO as it will interfere with the extended PDO library. Unless you are namespaced, you can only have one type of PDO class, and the extension PDO library will win.
This is wrong:


self::$instance = new PDO(xxxxxx);
self::$instance->setAttribute(xxxxxxxx);
self::$instance = new static();

Both PDO and static refer to the same class here since you named yours PDO. Instance should be of type this class since its a singleton object. What I see here would be an attempt to instantiate a PDO object as the instance, followed by an attempt to instantiate this object as its instance (also named PDO, but will not work since you cannot have 2x classes with the same name without a namespace).



class PDODriver
{
private static $instance;
private $connection;

private function __construct($sConnection) // lol too much java lately :P
{
$this->connection = new PDO($sConnection);
}

public static function getInstance()
{
if (self::$instance === null)
{
self::$instance = new static('driver connection string');
self::$instance->connection->setAttribute('xxx', 'xxx');
}

return self::$instance;
}

public function doQuery($sQry)
{
$db = $this->connection;
// go from here; I don't know what $QUERY in the original is since its not assigned anywhere
}
}

$db = PDODriver::getInstance();
$db->doQuery('tablename');


Connection class can simply return a passthrough of the getConnection type and chain it directly to the drivers getInstance. That will work if you want it to have a typeof PDO[Driver], whilst if you want a typeof Connection you would control the instance as well at the Connection level. If you implement a common interface, then you could do either and both would be valid as a typehint on the interface.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum