c# TempData equivalent in php

别来无恙 提交于 2019-11-29 12:49:04

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!