PHP, Singleton and $.ajax


PHP, Singleton and $.ajax

$.ajax(jQuery)似乎不能很好地与PHP Singleton配合使用。

我有一个简单的类定义如下:

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";
         ...
    }
}

我还有一个helper.php文件,用于获取singleton对象,然后执行一些操作。即:

<?php
require "MySingleton.php";
$singleton = MySingleton::getInstance();
$singleton->someFunction();
$singleton->someOtherFunction();
?>

在我的index.php中,我尝试使用$.ajax为我做一些事情:

$.each(data, function(key, value) {
            $.ajax({
                url: 'helper.php',
                type: 'POST',
                data: someData,
                dataType: 'JSON'
            }).always(function(result) {
                ...
            });
});//each

正如您在我的jQuery代码中看到的,我已经调用了$.ajax几次了。

我跟踪了MySingleton,它没有返回相同的实例,而是创建了几次(取决于$.each循环大小)。

我读过一篇文章:http://www.daniweb.com/web-development/php/threads/393405/php-singletone-pattern-in-php-files-where-ajaxs-requests-are-sent

发生这种情况是因为singleton模式只能在同一请求期间工作。在我的例子中,我有一些ajax请求(同样,基于$.each循环),这就是为什么它从未工作过。

我使用singleton对象的原因是因为我不想建立多个数据库连接,而且MySingleton将有一个数组(用于存储一些对象),在MySingletton类中,我将使用该数组临时存储一些信息,而不将其保存回数据库)

那么,有没有办法解决我的问题?我真的很想使用$.ajax和PHP Singleton。

在请求之间保存数据的唯一方法是将数据存储在某个地方。这基本上意味着会话、文件或数据库中。

我不认为一次加载所有数据比只加载一条记录慢,因为如果这个加载时间是创建请求、创建数据库连接等,那么90%的加载时间都是创建请求和数据库连接等。那么,如果一次加载全部数据太慢,你可以在上面添加缓存或其他东西,但我很确定它会足够快。