How to get user session data in action?

Hi all, I am new to slim. Currently am working to get session data after user login in action, the design pattern its ADR.

And this is middleware i get from odan

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Session Middleware.
 */
final class SessionMiddleware implements MiddlewareInterface
{
    /**
     * @var Session
     */
    private $session;

    /**
     * The constructor.
     *
     * @param Session $session The session handler
     */
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->session->start();

        return $handler->handle($request);
    }
}

Hi Emmanuel

To get the session onject you just need to add it to the constructor of the action class:

<?php

namespace App\Action\Demo;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Session\Session;

final class ExampleAction
{
    /**
     * @var Session
     */
    private $session;

    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    public function __invoke(
        ServerRequestInterface $request, 
        ResponseInterface $response
    ): ResponseInterface {

        // set a session value
        $this->session->set('mykey', 'my-value');

        // Read a session value
        $value = $this->session->get('mykey');
       
        // ...

       return $response;
    }
}

Example

PS: If you have specific question to the odan/slim4-skeleton, you can also create an issue here.

1 Like

thanks in advance for the solution.