setGlobalState and file locks

I wanted to use setGlobalState() for a simple pageview counter, but I am a little worried about the saving mechanism of the CStatePersister which, as far as I know, is used by default for saving global state. All the code does is:


file_put_contents($this->stateFile,serialize($state),LOCK_EX);

As far as I can tell, in the unlikely event of two PHP processes trying to save the state at roughly the same time, one of them will throw an error. Am I right? Is using the setGlobalState and getGlobalState safe?

The other request will wait until the lock is released.

However there is a different problem: When you set/get a state, Yii will first internally cache the states until the end of the request and then write them to the file. That means on concurrent requests this may happen:


Request #1 increases counter

Request #2 increases counter

Request #1 saves states

Request #2 now overwrites the states of Request #1

In the docs it says:

While this may be true for some global counter, "A global value" in this context is more like a config variable that changes rarely. You can see an example here.

So better use something else (database?) for such things as a pageview counter.

Great, I didn’t know about that!

As for the other issue I am aware of that problem, and I am torn between leaving it as is, since the counter is nothing of real importance, or moving it to DB. I guess I will do the latter.