northernwind
northernwind

Reputation: 637

singleton-registry pattern and object-interaction with ajax

My problem may be very specific i think. I already tryed to find some info about it, have viewed tons of sites, but with no success. And i'm a newbee in OO-php. I will try to explain issue without samples of code:

So, i have develop object-oriented php application. My Registry class implement singeltone pattern (have only one instance in whole app) and store objects that must be accessible in any part of application. At this moment i need to call JQuery AJAX to interact with user without page reloading. But calling php script via AJAX give me another instance of my Registry class (when i try to use registry in called php-file), this instance certainly empty (have no objects in array). I think this happened because AJAX calls works in different threads (may be i'm mistake). Anyway - is where some way to rich needed functionality using registry-pattern ? Or may be there is another ways to achieve it? I know that i can make my classes static, and use objects statically, but unfortunately i can't do it. I also know about global vars - it's no my way... Any help, please!

Upvotes: 0

Views: 353

Answers (1)

Brad
Brad

Reputation: 6332

So every single request to a PHP application is handled by a separate process on the server. No memory/data is shared across requests. That being the case, the Ajax request to the PHP script will not have access to your other request's info.

In order to handle this, You'll need to keep state of the data you're trying to store in some other way. Store it in the DB, Sessions, etc.

So say you have a "singleton-ish" list of objects that are items available in a store, the number in stock and their meta data.

in pseudo code:

$inventory = array(
       "cars" => array(SomeCarObject, AnotherCarObject), 
       "trucks" => array(SomeTruckObject, AnotherTruckObject)
    ); 

Because this is not kept in shared memory accross requests, every time you need to asynchronously operate on on this list, you'll need to fetch it (from where ever you're keeping state of it), modify it, then save it and respond appropriately.

Your flow might look something like this:

client request $inventory => server fetches state of $inventory, does stuff, resaves => sends $inventory back to client.

You will likely need to add a locking mechanism to the DB to indicate that another process is using it but that's something you'd need to exercise caution with because it can cause other requests to wait for something that is modifying your data to finish before they can finish. You do not want to introduce a race condition. http://en.wikipedia.org/wiki/Race_condition

Upvotes: 1

Related Questions