How do I save data in an application scope in PHP?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 11:42:25
Theodore R. Smith

2018 Edit: Time has not been kind to APC, especially since PHP 7 includes bundled support for Zend Optimizer+, which does largely the same thing (except the key-store). These days, the key store aspect has been forked over into the APCu project.

However, in 2018, the preferred key-store of choice is Redis. See the ext-redis project for details.


PHP has an application scope of sorts. it's called APC (Alternative PHP Cache).

Data should be cached in APC if it meets the following criteria:

  1. It is not user session-specific (if so, put in $_SESSION[])
  2. It is not really long-term (if so, use the file system)
  3. It is only needed on one PHP server (if not, consider using memcached)
  4. You want it available to every page of your site, instantly, even other (non-associated) PHP programs.
  5. You do not mind that all the data stored in it is lost on Apache reload/restart.
  6. You want data access far faster than file-based, memcached, or (esp.) database-based.

APC is installed on a great many hosts already, but follow the aforementioned guide to get installed on your box. Then you do something like this:

if (apc_exists('app:app_level_data') !== false)
{
    $data = apc_fetch('app:app_level_data');
}
else
{
    $data = getFromDB('foo');
    apc_store('app:app_level_data', $data);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!