ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### **Session** ### Extending Laravel with a custom session driver is just as easy as extending the cache system. Again, we will use the extend method to register our custom code: ~~~ <!-- lang:php --> Session::extend('mongo', function($app) { // Return implementation of SessionHandlerInterface }); ~~~ Note that our custom session driver should implement the ``SessionHandlerInterface``. This interface is included in the PHP 5.4+ core. If you are using PHP 5.3, the interface will be defined for you by Laravel so you have forward-compatibility. This interface contains just a few simple methods we need to implement. A stubbed MongoDB implementation would look something like this: ~~~ <!-- lang:php --> class MongoHandler implements SessionHandlerInterface { public function open($savePath, $sessionName) {} public function close() {} public function read($sessionId) {} public function write($sessionId, $data) {} public function destroy($sessionId) {} public function gc($lifetime) {} } ~~~ Since these methods are not as readily understandable as the cache ``StoreInterface``, let's quickly cover what each of the methods do: * The ``open`` method would typically be used in file based session store system. Since Laravel ships with a ``native`` session driver that uses PHP's native file storage for sessions, you will almost never need to put anything in this method. You can leave it as an empty stub. It is simply a fact of poor interface design (which we'll discuss later) that PHP requires us to implement this method. * The ``close`` method, like the ``open`` method, can also usually be disregarded. For most drivers, it is not needed. * The ``read`` method should return the string version of the session data associated with the given ``$sessionId``. There is no need to do any serialization or other encoding when retrieving or storing session data in your driver, as Laravel will perform the serialization for you. * The ``write`` method should write the given`` $data`` string associated with the ``$sessionId`` to some persistent storage system, such as MongoDB, Dynamo, etc. * The ``destroy`` method should remove the data associated with the ``$sessionId`` from persistent storage. * The ``gc`` method should destroy all session data that is older than the given ``$lifetime``, which is a UNIX timestamp. For self-expiring systems like Memcached and Redis, this method may be left empty. Once the ``SessionHandlerInterface`` has been implemented, we are ready to register it with the Session manager: ~~~ <!-- lang:php --> Session::extend('mongo', function($app) { return new MongoHandler; }); ~~~ Once the session driver has been registered, we may use the ``mongo`` driver in our ``app/config/session.php`` configuration file. > ### **Share Your Knowledge** ### > > Remember, if you write a custom session handler, share it on Packagist!