1

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?

4

3 回答 3

6

正如其他人指出的那样,使用会话来启用 TempData。这是一个简单的 PHP 实现:

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

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

测试:

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

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

不幸的是,我们不能用静态类来实现 ArrayAccess。

于 2011-09-22T12:09:54.720 回答
2

你在 PHP 中没有这个,但你自己实现它应该不会太难。实际实施取决于您的确切需求。

  • 您需要跨用户的数据还是为每个用户分开数据?
  • 你希望它有一个默认的过期时间吗?
  • 您是否希望它只是在活动请求中,还是应该一直存在直到有人检索它?
  • 是否可以接受“未命中”(请参阅​​ memcached)或者您想确保在请求时找到数据?
于 2011-09-22T11:48:59.867 回答
1

正如@AVD 所说,没有这样的命令。我真的不明白为什么。TempData 的作用是它允许您保存一些值/对象以往返于服务器。

如果您确实在您的网站中使用 Sessions,那么不使用 Session 来存储这些值是没有问题的。会话存储放置在服务器上,用户由每次发送到服务器的 sessionid 标识。

我能看到的唯一性能损失是,如果您要在运行 http 处理程序的进程之外运行会话存储。否则它们都在内存中,应该很快。

于 2011-09-22T11:51:08.450 回答