Skip to content

Commit da706aa

Browse files
committed
Avoid hitting session each time
1 parent 5abc4ed commit da706aa

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

src/Auth/Storage/SessionStorage.php

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ class SessionStorage implements StorageInterface
2525

2626
use InstanceConfigTrait;
2727

28+
/**
29+
* User record.
30+
*
31+
* @var array
32+
*/
33+
protected $_user;
34+
2835
/**
2936
* Session object.
3037
*
@@ -56,15 +63,16 @@ public function __construct(Request $request, array $config = [])
5663
/**
5764
* Get user record from session.
5865
*
59-
* @return array|null
66+
* @return array|null User record if available else null.
6067
*/
6168
public function get()
6269
{
63-
if (!$this->_session->check($this->_config['key'])) {
64-
return;
70+
if ($this->_user) {
71+
return $this->_user;
6572
}
6673

67-
return $this->_session->read($this->_config['key']);
74+
$this->_user = $this->_session->read($this->_config['key']);
75+
return $this->_user;
6876
}
6977

7078
/**
@@ -77,6 +85,8 @@ public function get()
7785
*/
7886
public function set(array $user)
7987
{
88+
$this->_user = $user;
89+
8090
$this->_session->renew();
8191
$this->_session->write($this->_config['key'], $user);
8292
}
@@ -90,6 +100,8 @@ public function set(array $user)
90100
*/
91101
public function remove()
92102
{
103+
unset($this->_user);
104+
93105
$this->_session->delete($this->_config['key']);
94106
$this->_session->renew();
95107
}

tests/TestCase/Auth/Storage/SessionStorageTest.php

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*
1010
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
1111
* @link http://cakephp.org CakePHP(tm) Project
12-
* @since 2.0.0
12+
* @since 3.1.0
1313
* @license http://www.opensource.org/licenses/mit-license.php MIT License
1414
*/
1515
namespace Cake\Test\TestCase\Auth;
@@ -62,11 +62,6 @@ public function testSet()
6262
*/
6363
public function testGet()
6464
{
65-
$this->session->expects($this->once())
66-
->method('check')
67-
->with('Auth.AuthUser')
68-
->will($this->returnValue(true));
69-
7065
$this->session->expects($this->once())
7166
->method('read')
7267
->with('Auth.AuthUser')
@@ -76,6 +71,22 @@ public function testGet()
7671
$this->assertSame($this->user, $result);
7772
}
7873

74+
/**
75+
* Test get from local var
76+
*
77+
* @return void
78+
*/
79+
public function testGetFromLocalVar()
80+
{
81+
$this->storage->set($this->user);
82+
83+
$this->session->expects($this->never())
84+
->method('read');
85+
86+
$result = $this->storage->get();
87+
$this->assertSame($this->user, $result);
88+
}
89+
7990
/**
8091
* Test remove
8192
*

0 commit comments

Comments
 (0)