HomePHP Page 3 - Using Session Handling Objects to Maintain the State of Applications with PHP Sessions
Developing an object-oriented session management module - PHP
Here you have it. The tutorial that you were waiting for! Welcome to the concluding part of the series “Maintaining the state of applications with PHP sessions.” In several tutorials, this series goes through the key points of managing sessions in PHP, and explores some of their most advanced features, such as developing user-defined session storage modules and using session handling objects.
Actually, creating an object-oriented session handling class is much simpler than you might have thought initially. The nitty-gritty of the whole development process rests on converting the prior callback functions to methods of the session handling class. In accordance with this idea, the basic structure of a session managing class can be defined like this:
// define 'SessionHandler' class
class SessionHandler { function SessionHandler(){ // code to register class methods goes here } function openSession(){ // no specific implementation is required here return true; } function closeSession(){ // no specific implementation is required here return true; } function readSession(){ // code to read session data goes here } function writeSession(){ // code to write session data goes here } function gcSession(){ // code to delete garbage session data goes here } }
As shown above, the skeleton of the corresponding session handling class is basically made up of the previous six callback functions, which of course have been defined as class methods. At first glance, you can see that encapsulating all the session handling methods behind the structure of a class comes in very useful for constructing a centralized mechanism to manage sessions within a specific PHP application.
I don't mean that an object-based approach is better that a procedural approach; that would be a misconception. I just want you to realize the convenience of having all the methods integrated into one class, which can be very handy in case you’re developing a Web application purely comprised of PHP objects.
At this point, you saw how the structure of the session handling class looks. Now, it’s time to leap forward and provide a specific implementation for each of its methods. Keep reading to learn more.