I am developing a Object Oriented website with PHP while using some design patterns I just learnt. I have a singleton class for the Database and Some other classes which does some database operations using an instance of the Database class.
Classes,
- Database (singleton)
- User
- Node
- Sensor
class Database {
//adaptor variable
private $db;
//singleton instance
private static $instance=NULL;
private $config = array(
'host' => 'localhost',
'username' => 'XXXXXXX',
'password' => '',
'dbname' => 'XXX'
);
private function __construct() {
try
{
echo "using construct";
//adaptor
$this->db = new PDO('mysql:host=' . $this->config['host'] . ';dbname=' . $this->config['dbname'], $this->config['username'], $this->config['password']);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e->getMessage());
exit();
}
}
public static function getConnection()
{
if(self::$instance==NULL)
{
self::$instance = new Database();
}
return self::$instance;
}
public function prepare($sql)
{
return $this->db->prepare($sql);
}
}
Other classes uses the getConnection function to get the singleton instance
class User extends Visitor {
//* has getters and setters(setters via database only)
private $db;
private $username; //*
private $email; //*
private $confirmed;//*
private $nodes;
private $id;
public function __construct() {
$this->db = Database::getConnection();
$argv = func_get_args();
switch( func_num_args() ) {
case 0:
self::__construct1();
break;
case 1:
self::__construct2($argv[0]);
break;
}
}
}
So this is the basic structure of every class.
I am using singleton for the database because i don't want too many connections happening in my server which would eat up my memory.
To check whether the singleton is working properly, i have added an echo at the constructor of the database class.
So all in all, this should work properly. And it was working properly until I added some more methods to the User class(Ability to delete nodes, I have 550 lines in the user class and as I suppose, it shouldn't matter)
The error I am getting is of sort like this
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\xampp\htdocs\WeatherCenter\lib\classes\Database.php on line 18
That is pointing to the config array in the database class. First I got this at my "Node" class. Then I added some
unset()
Methods into that class and then it got moved to the Database class. I am not sure why this problem is occurring, I don't have any repetitive structures in the Database class(but I have at the Node class)
ini_set('memory_limit', '-1'); is not an option since I don't want to use a way around, I need to debug the error here.
I will upload the necessary files you require,
Thanks in advance, Bhashithe