PHP:持久变量值 [英] PHP: persistent variable value

查看:39
本文介绍了PHP:持久变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取文件并进行一些计算,而不是将计算结果保存在变量中.

I have to read a file and do some computation, than save the result of this computation inside a variable.

我只需要这样做一次.在 Java + Servlet 中,我可以使用 servlet 容器来实现这一点,例如,单例模式.

I just need to do this once. In Java + Servlet I can do this using a servlet container and, for instance, the singleton pattern.

我知道在 PHP 中我不能这样做.哪种方法更好?在 DB 上保存计算(或传输数据)?

I know that in PHP I can't act like this. Which is the better way to do this? Save the computation (or transfer the data) on DB?

推荐答案

不,它不会像 Java Servlets 那样工作.您必须找到解决方法.

No, it won't work like with Java Servlets. You'll have to find a workaround.

首先,我假设通常使用 $_SESSION、$_COOKIE 或 $_REQUEST 对您来说是不切实际的,因为您想保存每个服务器(或每个应用程序)而不是每个用户会话"的状态.

First, I assume that using $_SESSION, $_COOKIE or $_REQUEST in general isn't practicable to you as you want to save the state per server (or per application) and not per 'User Session'.

在您的情况下使用数据库听起来可行.在常规应用程序设计中,它将是最常见的解决方案.

Using a database sounds practicable in your case. In a regular application design it will be the most common solution.

您也可以使用 PHP 的序列化功能执行类似操作:

Also you can do something like this, using the serialization capabilities of PHP:

<?php

$resultfile = 'result.dat';
if(!file_exists($resultfile)) {
    $result = compute_result('foo bar');
    file_put_contents($resultfile, serialize($result));
} else {
    $result = unserialize(file_get_contents($resultfile));
}

使用 PHP 的 serialize() 尝试在

Using PHP's serialize() attempt is especially practicable when

  • 您在一个只有 PHP 的环境中
  • $result 是一种复杂的数据类型,但您不想创建数据库结构并将 $result 也映射到它
  • You are in a PHP only environment
  • $result is a complex datatype but you don't want to create a database structure and map $result too it

如果您不是在仅使用 PHP 的环境中,您可能更喜欢其他序列化格式,如 JSON 或 XML.

If you are not in a PHP only environment you might prefer other serialization formats as JSON or XML.

也可以将序列化结果作为字符串存储在数据库中而不是文件中.将其保存到数据库而不是文件将使应用程序更具可扩展性,因为访问同一数据库(集群)的所有服务器都可以使用结果.

Also the serialization result can be stored as a string in a database instead of a file. Saving it to a database instead of a file would make the application more scalable as the result would be available to all servers that access the same database (cluster).

简而言之:我建议将数据库与序列化结合使用.

In short: I would suggest using a database maybe combined with serialization.

这篇关于PHP:持久变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆