我有一个代码,并尝试更改此行:
$sth = $db->prepare(Utils::prepareSQLPrefix($sql, Config::get('DB_PREFIX')));
在我的DatabaseFactory类中扩展某种$ db-> prepare函数(替换查询前缀)。
$db = DatabaseFactory::getFactory()->getConnection();
$sql = ' SELECT
`id`, `manifest`
FROM
`#__extensions`
WHERE
`name` = :name
LIMIT 1';
$sth = $db->prepare(Utils::prepareSQLPrefix($sql, Config::get('DB_PREFIX')));
$sth->execute(array('name' =>$extension->component_name));
$result = $sth->fetch();
我的DatabaseFactory类:
class DatabaseFactory {
private static $factory;
private $database;
public static function getFactory()
{
if (!self::$factory) {
self::$factory = new DatabaseFactory();
}
return self::$factory;
}
public function getConnection() {
if (!$this->database) {
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->database = new PDO(
Config::get('DB_TYPE') . ':host=' . Config::get('DB_HOST') . ';dbname=' .
Config::get('DB_NAME') . ';port=' . Config::get('DB_PORT') . ';charset=' . Config::get('DB_CHARSET'),
Config::get('DB_USER'), Config::get('DB_PASS'), $options
);
}
return $this->database;
}
}
My Utils课程:
class Utils {
public static function prepareSQLPrefix($sql, $prefix) {
return str_replace('#__', $prefix, $sql);
}
}
我该怎么做?谢谢!
答案 0 :(得分:1)
我想你应该创建一个扩展PDO
并重新定义prepare
函数的新类:
class myPDO extends PDO {
public function prepare ($sql, $options = NULL) {
$sql = Utils::prepareSQLPrefix($sql, Config::get('DB_PREFIX'));
return parent::prepare($sql, $options);
}
}
然后您将工厂getConnection
更改为:
public function getConnection() {
if (!$this->database) {
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->database = new myPDO(
Config::get('DB_TYPE') . ':host=' . Config::get('DB_HOST') . ';dbname=' .
Config::get('DB_NAME') . ';port=' . Config::get('DB_PORT') . ';charset=' . Config::get('DB_CHARSET'),
Config::get('DB_USER'), Config::get('DB_PASS'), $options
);
}
return $this->database;
}
然后代替:
$sth = $db->prepare(Utils::prepareSQLPrefix($sql, Config::get('DB_PREFIX')));
你可以:
$sth = $db->prepare($sql);
获得相同的预期结果