Middleware to start a php session using the request data and close it after return the response.
- PHP >= 7.1
- A PSR-7 http message implementation and PSR-17 http factory implementation (ex. Embryo-Http)
- A PSR-15 http server request implementation (ex. Embryo-Middleware)
Using Composer:
$ composer require davidecesarano/embryo-session
Creates a middleware for setting session item:
class TestSetSessionMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$session = $request->getAttribute('session');
$session->set('name', 'World');
$response = $handler->handle($request);
return $response->write('Hello '.$session->get('name').'</p><p><a href="test.php">Other Page</a></p>');
}
}
Creates another middleware for getting session item:
class TestGetSessionMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$session = $request->getAttribute('session');
$response = $handler->handle($request);
return $response->write('Hello '.$session->get('name').'</p>');
}
}
Adds middleware to dispatcher:
$session = new Session;
$middleware = new RequestHandler;
$middleware->add(
(new SessionMiddleware)
->setSession($session)
->setOptions([
'use_cookies' => false,
'use_only_cookies' => true
])
);
$middleware->add(TestSetSessionMiddleware::class);
$middleware->add(TestGetSessionMiddleware::class);
$response = $middleware->dispatch($request, $response);
The session name. If it's not provided, use the php's default.
Array of options passed to session_start()
.
The session request attribute. If it's not provided, use $request->getAttribute('session')
.
You may retrieve an item from the session and you may also pass a default value as the second argument to the get
method:
$session->get('key', 'default');
If you would like to retrieve all the data in the session, you may use the all
method:
$session->all();
To determine if an item is present in the session, you may use the has
method. The has method returns true
if the item is present and is not null
:
if ($session->has('key')) {
//...
}
The set
method may be used to set a new value onto a session:
$session->set('name', 'value');
You may wish to store items in the session only for the next request using the flash
method:
$session->flash('name', 'value');
The remove
method will remove a piece of data from the session. If you would like the remove all data from the session, you may use the clear
method:
$session->remove('name');
$session->clear();