4

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

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

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?

7
  • 5
    apc_cache if you have that installed Commented Dec 28, 2012 at 19:56
  • Why can't you do a singleton in PHP? Commented Dec 28, 2012 at 19:58
  • 1
    @JaredFarrish because the variable will not persist between multiple requests Commented Dec 28, 2012 at 19:59
  • @Antonio That's what sessions are for us1.php.net/manual/en/book.session.php, or do you mean you need a global state for all users? Commented Dec 28, 2012 at 19:59
  • @MichaelBerkowski sessions are relative to a single user, am I wrong? edit: yes, I need some global state, sorry you edited :) Commented Dec 28, 2012 at 20:00

1 Answer 1

9

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

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.

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));
}

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

  • 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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just as an additional suggestion: if you need to access this global state using another language (maybe Java), using a format like JSON might be easier.
Yes, thats right. I updated the answer according to your comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.