A better solution
Think Facebook is using flat files to store session info for the millions of users online at any given moment? Think again.If your site is growing and slowing, improving how sessions are handled can bring back life to your site. There are several ways to do this, each with its own pros and cons, but in this article we will use a reliable, performant, and easy to setup solution that probably already exists on your server…the database.
Databases aren’t just for content
Databases can be significantly more performant than flat files, and many more sessions can be handled at one time, making them an ideal solution for sites looking to boost performance.Fortunately, PHP provides developers with the ability to setup custom session handlers, using any type of backend. The downside is that setting this up can be a bit involved and complicated. Enter Zend_Session.
Custom session handling made easy
The Zend_Session component of the Zend Framework makes custom session handling a breeze. What’s even better, is that the Zend Framework provides a built in class for using a database as a session handler: Zend_Session_SaveHandler_DbTable. To get started, we first need to create a table to hold our sessions:
CREATE
TABLE
`session` (
`id`
char
(32),
`modified`
int
,
`lifetime`
int
,
`data` text,
PRIMARY
KEY
(`id`)
);
$db
= Zend_Db::factory(
'Pdo_Mysql'
,
array
(
'host'
=>
'example.com'
,
'username'
=>
'dbuser'
,
'password'
=>
'******'
,
'dbname'
=>
'dbname'
));
$config
=
array
(
'name'
=>
'session'
,
'primary'
=>
'id'
,
'modifiedColumn'
=>
'modified'
,
'dataColumn'
=>
'data'
,
'lifetimeColumn'
=>
'lifetime'
,
'db'
=>
$db
);
Zend_Session::setSaveHandler(
new
Zend_Session_SaveHandler_DbTable(
$config
));
//start your session
Zend_Session::start();
And that’s it! Place the above code in an early running part of your application, and any subsequent calls to Zend_Session_Namespace or $_SESSION variables directly will use your database instead of flat files. Garbage collection (the removal of old records) is done automatically for you.
Conclusion
By following these simple steps, you can improve the performance and stability of your web application by storing session data in a reliable and performant container, the database. Any database system can be used, from Mysql to Postgresql, to Sqlite, and all will increase the reliability and speed of your site.Improving session handling with the Zend Framework is so simple that it should be one of the first things you do when creating a new site or application.
Nguon : http://zendcoding.com/how-to-use-a-database-for-session-handling-in-the-zend-framework
Không có nhận xét nào:
Đăng nhận xét