Optimized way to read settings from database only once in PHP
I'm working on a big project with several http servers that use one main sql database.
The project has many settings that are frequently used(almost every re开发者_如何学Goquest). The settings are stored in the main sql database.
I wanted to know, if there is some way to initialize settings only once in php, because it makes no sense for every request to go and read same setting from sql server over and over again, it feels like a waste of resources.
Thanks in advance
2 solutions:
Create a (perhaps also PHP) script that exports settings from database into a plain text file, and includes that file on every http server;
use a memory cache server like http://memcached.org/ and preload data there from an external script, then have http servers connect to memcache instead of SQL.
Edit: Other than that, PHP does not give you a real web application, where you "run" your application and it has its own memory and persistant, global variables. This is one of the reasons I personally got tired of PHP and moved to Python (and Django, specifically).
Hard code these settings in your PHP code.
// Your current code, somthing like this:
$setting_1 = getDataFromMySQL('setting1');
// Hard coded
$setting_1 = TRUE;
You can use shared memory in php if it is compiled that way.
Another possibility is that you store a combined value of your settings as PHP code in one field (a PHP array for example), then you can read them all with only one query to the DB server. Of course this cached value have to be updated when settings change.
APC is the best solution if you are using a single server, otherwise I would go with memcached. However, you may also consider a MYSQL memory table, it is very efficient for fast reads and writes. Another solution is using Linux to keep and call settings with Linux exec. However, this might be a trouble and there might be some security issues. Also let me remind you that efficient INNODB indexes can help you a lot. MYISAM is also considered a good "read" performer, however my benchmarks show me that INNODB indexes are faster.
You can store the settings in the user's session -
session_start();
if (!isset($_SESSION['settings'])) {
$settings_array = //pulled from database
$_SESSION['settings'] = $settings_array;
}
That way, it'll only query once per user
You could use a session to store those settings.
精彩评论