Jack Juiceson
Jack Juiceson

Reputation: 830

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 request). 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

Upvotes: 2

Views: 343

Answers (6)

ufucuk
ufucuk

Reputation: 475

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.

Upvotes: 0

Gnudiff
Gnudiff

Reputation: 4305

2 solutions:

  1. Create a (perhaps also PHP) script that exports settings from database into a plain text file, and includes that file on every http server;

  2. 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).

Upvotes: 3

gnur
gnur

Reputation: 4733

You could use a session to store those settings.

Upvotes: -1

Sam Dufel
Sam Dufel

Reputation: 17598

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

Upvotes: -1

vbence
vbence

Reputation: 20333

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.

Upvotes: 0

powtac
powtac

Reputation: 41050

Hard code these settings in your PHP code.

// Your current code, somthing like this:
$setting_1 = getDataFromMySQL('setting1');

// Hard coded
$setting_1 = TRUE;

Upvotes: 0

Related Questions