Question

I know I can explicitly set and unset a Session manually but I believe this is worth to ask. In c#, there is a dictionary called TempData which stores data until the first request. In other words, when TempData is called, it is automatically unset. For a better understanding here is an example:

Controller1.cs:

TempData["data"] = "This is a stored data";

Model1.cs:

string dst1 = TempData["data"]; // This is a stored data
string dst2 = TempData["data"]; // This string will be empty, if an exception is not raised (I can't remember well if an exception is raised)

So basically, this is just something like a session for 1 use only. Again, I know that I can set and unset explicitly in php, but still, does php has a function like this one?

Was it helpful?

Solution

As the others have pointed out, uses sessions to enable TempData. Here is a simple PHP implementation:

class TempData {
    public static function get($offset) {
        $value = $_SESSION[$offset];
        unset($_SESSION[$offset]);
        return $value;
    }

    public static function set($offset, $value) {
        $_SESSION[$offset] = $value;
    }
}

Test:

TempData::set("hello", "world");
var_dump($_SESSION); // array(1) { ["hello"]=> string(5) "world" }

TempData::get("hello"); // => world
var_dump($_SESSION); // array(0) { } 

Unfortunately, we can not implement ArrayAccess with a static class.

OTHER TIPS

You don't have that in PHP, but it shouldn't be too hard to implement it yourself. The actual implementation depends on your exact needs.

  • Do you need that data across users or separated for each user?
  • Do you want it to have a default expiration time?
  • Do you want it just in the active request or should it persist until someone retrieves it?
  • Are "misses" acceptable (see memcached) or do you want to be sure you find the data when you request it?

As @AVD tells, there is no such command. And I can't really see why. The thing with TempData is that it allows you to save some values / objects for a roundtrip to the server.

If you do use Sessions in your website there is no issue to not use Session to store these values. Session storage is placed on the server and the users is identified by a sessionid which is sent to the server each time.

The only performance penalty I can see is if you were to run your session storage outside your process running the http handler. Otherwise they are both in memory and should be pretty fast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top