Reputation: 690
It seems like $.ajax (jQuery) doesn't work well with PHP Singleton.
I have a simple Class defined like this:
class MySingleton
{
protected static $instance = null;
private $array;
protected function __construct()
{
...
$this->array = array();
//get something from database,
$this->array[] = object from database;
$this->array[] = object from database;
...
}
protected function __clone()
{
}
public static function getInstance()
{
if (!isset(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
public function someFunction() {
$this->array[0]->someField = "set something without saving it to database";
...
}
}
I also have a helper.php file that get the singleton object then do something. ie:
<?php
require "MySingleton.php";
$singleton = MySingleton::getInstance();
$singleton->someFunction();
$singleton->someOtherFunction();
?>
In my index.php, I tried to use the $.ajax to do something for me:
$.each(data, function(key, value) {
$.ajax({
url: 'helper.php',
type: 'POST',
data: someData,
dataType: 'JSON'
}).always(function(result) {
...
});
});//each
as you can see in my jQuery code, I have called $.ajax a few times.
I traced the MySingleton, and instead of returning the same instance, it created a few times (depending on the $.each loop size).
I have read an article: http://www.daniweb.com/web-development/php/threads/393405/php-singletone-pattern-in-php-files-where-ajaxs-requests-are-sent
and this happens because of the singleton pattern will only work during the same request. In my case I have a few ajax requests (again, based on the $.each loop) and that's why it never worked.
The reason I am using a singleton object is because I don't want to make multiple database connections, also MySingleton will have an array (which will be used to store some objects) and in the MySingleton class I will use the array to temporary store some information without saving it back to the database)
So is there anyway to solve my problem? I really want to use the $.ajax and PHP Singleton.
Upvotes: 2
Views: 1072
Reputation: 2191
The only way to save data between requests is storing it somewhere. Which basically means either the session or a file or in the database.
I don't think that loading all data at once is slower than loading only one record, because 90% if this loading time is creating the request, creating database connection etc. So how about you try to load all the data at once and if its too slow you can add a cache or something else on top of it, but I am pretty sure it will be fast enought.
Upvotes: 1