Browse Source

Avoid hitting session each time

ADmad 10 years ago
parent
commit
da706aaf43

+ 16 - 4
src/Auth/Storage/SessionStorage.php

@@ -26,6 +26,13 @@ class SessionStorage implements StorageInterface
     use InstanceConfigTrait;
 
     /**
+     * User record.
+     *
+     * @var array
+     */
+    protected $_user;
+
+    /**
      * Session object.
      *
      * @var \Cake\Network\Session
@@ -56,15 +63,16 @@ class SessionStorage implements StorageInterface
     /**
      * Get user record from session.
      *
-     * @return array|null
+     * @return array|null User record if available else null.
      */
     public function get()
     {
-        if (!$this->_session->check($this->_config['key'])) {
-            return;
+        if ($this->_user) {
+            return $this->_user;
         }
 
-        return $this->_session->read($this->_config['key']);
+        $this->_user = $this->_session->read($this->_config['key']);
+        return $this->_user;
     }
 
     /**
@@ -77,6 +85,8 @@ class SessionStorage implements StorageInterface
      */
     public function set(array $user)
     {
+        $this->_user = $user;
+
         $this->_session->renew();
         $this->_session->write($this->_config['key'], $user);
     }
@@ -90,6 +100,8 @@ class SessionStorage implements StorageInterface
      */
     public function remove()
     {
+        unset($this->_user);
+
         $this->_session->delete($this->_config['key']);
         $this->_session->renew();
     }

+ 17 - 6
tests/TestCase/Auth/Storage/SessionStorageTest.php

@@ -9,7 +9,7 @@
  *
  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  * @link          http://cakephp.org CakePHP(tm) Project
- * @since         2.0.0
+ * @since         3.1.0
  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
  */
 namespace Cake\Test\TestCase\Auth;
@@ -63,11 +63,6 @@ class SessionStorageTest extends TestCase
     public function testGet()
     {
         $this->session->expects($this->once())
-            ->method('check')
-            ->with('Auth.AuthUser')
-            ->will($this->returnValue(true));
-
-        $this->session->expects($this->once())
             ->method('read')
             ->with('Auth.AuthUser')
             ->will($this->returnValue($this->user));
@@ -77,6 +72,22 @@ class SessionStorageTest extends TestCase
     }
 
     /**
+     * Test get from local var
+     *
+     * @return void
+     */
+    public function testGetFromLocalVar()
+    {
+        $this->storage->set($this->user);
+
+        $this->session->expects($this->never())
+            ->method('read');
+
+        $result = $this->storage->get();
+        $this->assertSame($this->user, $result);
+    }
+
+    /**
      * Test remove
      *
      * @return void