slim-session
Simple middleware for Slim Framework 3, that allows managing PHP
built-in sessions and includes a Helper
class to help you with the $_SESSION
superglobal.
For the middleware version for Slim Framework 2, please check out the slim-2
branch in this repository.
Installation
Add this line to require
block in your composer.json
:
"bryanjhv/slim-session": "~3.0"
Or, run in a shell instead:
composer require bryanjhv/slim-session:~3.0
Usage
$app = new \Slim\App;
$app->add(new \Slim\Middleware\Session([
'name' => 'dummy_session',
'autorefresh' => true,
'lifetime' => '1 hour'
]));
Supported options
lifetime
: How much should the session last? Default20 minutes
. Any argument thatstrtotime
can parse is valid.path
,domain
,secure
,httponly
: Options for the session cookie.name
: Name for the session cookie. Defaults toslim_session
(instead of PHP'sPHPSESSID
).autorefresh
:true
if you want session to be refresh when user activity is made (interaction with server).handler
: Custom session handler class or object. Must implementSessionHandlerInterface
as required by PHP.
Session helper
A Helper
class is available, which you can register globally or instantiate:
$container = $app->getContainer();
// Register globally to app
$container['session'] = function ($c) {
return new \SlimSession\Helper;
};
That will provide $app->session
, so you can do:
$app->get('/', function ($req, $res) {
// or $this->session if registered
$session = new \SlimSession\Helper;
// Check if variable exists
$exists = $session->exists('my_key');
$exists = isset($session->my_key);
$exists = isset($session['my_key']);
// Get variable value
$my_value = $session->get('my_key', 'default');
$my_value = $session->my_key;
$my_value = $session['my_key'];
// Set variable value
$app->session->set('my_key', 'my_value');
$session->my_key = 'my_value';
$session['my_key'] = 'my_value';
// Merge value recursively
$app->session->merge('my_key', ['first' => 'value']);
$session->merge('my_key', ['second' => ['a' => 'A']]);
$letter_a = $session['my_key']['second']['a']; // "A"
// Delete variable
$session->delete('my_key');
unset($session->my_key);
unset($session['my_key']);
// Destroy session
$session::destroy();
// Get session id
$id = $this->session::id();
return $res;
});
Contributors
Here are the big ones listed. 😄
TODO
- Complete
Helper
tests. (thanks @Zemistr) - Slim-specific tests (integration with Slim App).
License
MIT