diff --git a/src/Illuminate/Session/Store.php b/src/Illuminate/Session/Store.php index 19c4382fc91d..0f39ad0f5032 100755 --- a/src/Illuminate/Session/Store.php +++ b/src/Illuminate/Session/Store.php @@ -2,6 +2,7 @@ namespace Illuminate\Session; +use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Str; use SessionHandlerInterface; @@ -748,4 +749,24 @@ public function setRequestOnHandler(Request $request) $this->handler->setRequest($request); } } + + /** + * Get an item from the sessuib, or store the default value. + * + * @param string $key + * @param \Closure $callback + * @return mixed + */ + public function remember($key, Closure $callback) + { + // If the item exists in the session we will just return this immediately + // otherwise we will execute the given Closure and store the result + if (!is_null($value = $this->get($key))) { + return $value; + } + + $this->put($key, $value = $callback()); + + return $value; + } } diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php index f6273b9f07a3..7f05d85d7e8c 100644 --- a/tests/Session/SessionStoreTest.php +++ b/tests/Session/SessionStoreTest.php @@ -345,6 +345,17 @@ public function testKeyExists() $this->assertFalse($session->exists(['foo', 'baz', 'bogus'])); } + public function testRememberMethodCallsPutAndReturnsDefault() + { + $session = $this->getSession(); + $session->getHandler()->shouldReceive('get')->andReturn(null); + $result = $session->remember('foo', function () { + return 'bar'; + }); + $this->assertEquals('bar', $session->get('foo')); + $this->assertEquals('bar', $result); + } + public function getSession() { $reflection = new ReflectionClass('Illuminate\Session\Store');