2 ms·
Caching PHP objects: how to do it in 4 easy steps
- nuggien 18y agoI could only stand that yellow background for about 5 seconds before I hit the back button.
- senthil_rajasek 18y agoun/serializing to file system. Why is this better than letting mysql do the disk I/O for you?
- jws 18y agoDangerous code in that example: Step1: Don't chmod a directory 777. How about 770 (or maybe 775) with an appropriate owner and group. There is just no reason to allow a stranger or zero privilege nobody/nogroup hack to write arbitrary data into your cache. Step3: There is a race condition here that can corrupt your cache and cause sudden catastrophic performance problems. When the cache expires, until someone manages to rewrite the cache all readers will try to regenerate it and rewrite it. If you used this technique because you had database load issues you are in for a thumping. Worse, each will then write the cache, probably about the same time since they will be in lock step from the database IO, with an fopen/fwrite/fclose. You could end up with a muddle of a file. To fix: you could use some sort of lock to ensure only one reader tries to rebuild the cache, but that scares some programmers. For writing the file you should ALWAYS write to a temporary, unique filename, close, then rename the file to the proper filename. It is a tiny nuisance, but rename is atomic in unix land and no one will get a partially written file or one muddled by multiple writers. (For bonus performance, I'd add a random number to each "too old" check. That way the first process that decides it was too old would start the rebuild of the cache, but most of its temporal peers would probably not think it was too old and would happily use the cache. Otherwise you get a bunch of processes waiting for the rebuild.) Step 4: If you are on Apache. It can make things more fragile by spreading your site across the filesystems, but I prefer to put files like this off in an area of filesystem not under docroot. The danger is that when someone goes to move the site, they have to know about these other files as well. And finally: benchmark before and after. This can be a big performance win, but sometimes you can be surprised.