我想要使用的类使用变量in就是这样:
Class OrdersModel extends DatabaseFactory
{
public function userownsorder($id, $buysell)
{
//sql to run
$sql = "SELECT count(*) FROM orders
WHERE id = ?
AND user = ?
AND buysell = 'buy'";
//run the sql
$checkfield = $database->prepare($sql);
$checkfield->execute(array($id, Session::get('id')));
//return the results
return $checkfield->fetchColumn();
}
但是每次我想使用数据库时,我都需要像这样对它进行修改:
$database = DatabaseFactory::getFactory()->getConnection();
在每个函数中有点重复并且会使我的文件膨胀,有没有办法使用$ database而不是每次都使用它,我尝试了以下内容:
global $database = DatabaseFactory::getFactory()->getConnection();
和
function __construct()
{
$database = DatabaseFactory::getFactory()->getConnection();
}
但不起作用,我真的不想使用$this->database
,而只想使用变量$database
....这里是数据库类:
<?php
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) {
/**
* Check DB connection in try/catch block. Also when PDO is not constructed properly,
* prevent to exposing database host, username and password in plain text as:
* PDO->__construct('mysql:host=127....', 'root', '12345678', Array)
* by throwing custom error message
*/
try {
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
$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
);
} catch (PDOException $e) {
// Echo custom message. Echo error code gives you some info.
echo 'Database connection can not be estabilished. Please try again later.' . '<br>';
echo 'Error code: ' . $e->getCode();
// Stop application :(
// No connection, reached limit connections etc. so no point to keep it running
exit;
}
}
return $this->database;
}
}