The class I want to use use the variable in is like so:
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();
}
But each time I want to use the database I need to iniate it like so:
$database = DatabaseFactory::getFactory()->getConnection();
in each function which is a bit repetative and will bloat my files, is there a way to use the $database without iniating it each time, I have tried the following:
global $database = DatabaseFactory::getFactory()->getConnection();
and:
function __construct()
{
$database = DatabaseFactory::getFactory()->getConnection();
}
but neither work, I don't really want to use $this->database
but would rather just use the variable $database
.... here is the database class:
<?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;
}
}