Can I use $_SESSION as memcache?
Every time a page is loaded I connect to the database to fetch the settings
table where the basic application settings are stored. It looks uneficcient.开发者_运维知识库 I have an idea to temporary store the $settings
array in $_SESSION variable. So every time the script is started it checks if $_SESSION['settings'] is empty and loads the data from DB only if it is.
My questions are:
1)Is this normal practice or there are serious pitfalls?
2)Will this speed up my application?
It looks unefficient.
it looks or it IS inefficient?
I have an idea to temporary store the $settings array in $_SESSION variable.
That's wrong idea. Sessions are for personal data, not site-wide settings. If you want to read your settings from a file - include it!
Will this speed up my application?
Is anything wrong with your application speed at the moment?
I would guess performance benefits of this would be negligible at best, and potentially harmful at worst.
Either way $_SESSION isn't really intended to be used this way, it's for data relating to a specific user, and as a general rule I try to keep it as concise as possible.
A better solution you might consider is caching the settings locally as a PHP file, it's not too hard to script something up to generate a file that creates a simple key => value array from the database that you can include. e.g.
<?php
// myconfig.php
return array(
'mysetting' => 'value',
);
Then you can just include this file to get your config values:
<?php
// app.php
$config = include('myconfig.php');
echo $config['mysetting']; // 'value'
I would not recommend using PHP's $_SESSION
as a local cache. For each visitor that comes to your site, you'll need to populate that $_SESSION
variable. This is inefficient, since each visitor will get a session when they don't need. It's also difficult to manage, since changes to your settings
data won't immediately be populated into the $_SESSION
variable. I'd recommend something like memcached or even apc local object cache for this.
精彩评论